开发者

excel vba loop through worksheets and set values according to input

I'm trying to loop thru each worksheet and set 100 rows of column A to the value of an input parameter. I want each sheet to call an input box and have the column's values equ开发者_运维知识库al to that input but what is happening is that the 1st worksheet is getting the last input and all the sheets values for columnA are blank except for sheet 1.

Dim wkbkorigin As Workbook
Set wkbkorigin = Workbooks.Open("C:\bookB.xls")

For Each ThisWorkSheet In wkbkorigin.Worksheets  
    Subject = InputBox("Enter the 'Subject' field for " & ThisWorkSheet.Name & ":")
    For i = 1 To 100  
        Range("A2").Cells(i, 1) = Subject
    Next
Next


You may want to change:

Range("A2").Cells(i, 1) = Subject

to:

ThisWorkSheet.Range("A2").Cells(i, 1) = Subject

Range on its own will apply to the current worksheet (which, from your symptoms, is the first worksheet) so what you're doing is simply overwriting the cells in that worksheet each time.

That's why they end up with the last value entered, while the other sheets remain blank.


Also, there is no need to loop - simply use:

ThisWorkSheet.Range("A2:A100").Value = Subject

Which will be much faster

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜