Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 views
in Technique[技术] by (71.8m points)

vba - Loop for all worksheet in a workbook is not working

I would to copy paste the first cell of a sheet trough the last row for all sheets in a workbook and my code is not working, the code is done on the active sheet only.

Sub Macro5()
'
' Macro5

 Dim ws As Worksheet

 For Each ws In ActiveWorkbook.Worksheets

     Range("A2").Copy Destination:=Range("A3:A" & Cells(Rows.Count, "B").End(xlUp).Row)

 Next ws

End Sub

Thanks for your help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Looping the worksheets does not make them active. You want something like this.

    Dim WS As Excel.Worksheet
    Dim iIndex As Integer

    For iIndex = 1 To ActiveWorkbook.Worksheets.count
        Set WS = Worksheets(iIndex)
        With WS

        'Do something here.
            .Range("A2").Copy Destination:=.Range("A3:A" & .Cells(.Rows.Count, "B").End(xlUp).Row)
        End With
    Next iIndex

You could use the ws in your loop, but I always set the object.

 For Each ws In ActiveWorkbook.Worksheets
     ws.Range("A2").Copy Destination:=ws.Range("A3:A" & Cells(Rows.Count, "B").End(xlUp).Row)
 Next ws

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...