无法遍历所有工作表

时间:2017-12-11 05:18:03

标签: vba excel-vba loops excel

VBA初学者, 我正试图通过所有工作表循环代码。 但每当我尝试运行它时,它只会针对当前活动工作表执行。

 Sub test1()

 Dim ws As Worksheet
 Dim i As Integer
 Dim k As Integer

     For Each ws In ActiveWorkbook.Sheets

         For i = 1 To Cells(1, Columns.Count).End(xlToLeft).Column
             For k = Cells(Rows.Count, i).End(xlUp).Row To 3 Step -1

             Cells(k - 1, i) = Cells(k - 1, i) & ", " & Cells(k, i)

             Cells(k, i).Clear
             Next k

         Next i

     Next ws

 End Sub

提前致谢

1 个答案:

答案 0 :(得分:3)

您需要在Cells前加上ws.Cells等工作表对象。以下是您的代码的工作版本。试一试。

Sub test1()

 Dim ws As Worksheet
 Dim i As Integer
 Dim k As Integer

     For Each ws In ActiveWorkbook.Sheets

         For i = 1 To ws.Cells(1, Columns.Count).End(xlToLeft).Column
             For k = ws.Cells(Rows.Count, i).End(xlUp).Row To 3 Step -1

             ws.Cells(k - 1, i) = ws.Cells(k - 1, i) & ", " & ws.Cells(k, i)

             ws.Cells(k, i).Clear
             Next k

         Next i

     Next ws

 End Sub