2014-09-20 92 views
4

VBA初学者在这里,我正在处理的程序有一个小问题。Excel VBA循环遍历多个工作表

我需要从第一个工作表中的列B中的最后一个单元格复制数据,并将其粘贴到另一个工作表xws中的列A中,并使用数据为其他五个工作表重复此操作。

下面的代码,它不工作的方式应该:

Sub exercise() 

    Dim ws As Worksheet 
    Dim rng As Range 
    'Finding last row in column B 
    Set rng = Range("B" & Rows.Count).End(xlUp) 

    For Each ws In ActiveWorkbook.Worksheets 
     'Don't copy data from xws worksheet 
     If ws.Name <> "xws" Then 
      'Storing first copied data in A1 
      If IsEmpty(Sheets("xws").[A1]) Then 
       rng.Copy Sheets("xws").Range("A" & Rows.Count).End(xlUp) 
      'Storing next copied data below previously filled cell 
      Else 
       rng.Copy Sheets("xws").Range("A" & Rows.Count).End(xlUp).Offset(1, 0) 
      End If 
     End If 
    Next ws 
End Sub 

没有与WS问题。但是每当我在if语句之前或之前将其放在范围内(set rng = ...),我都会得到错误。

在此先感谢任何指针。

+0

什么不行? – Cullub 2014-09-20 22:35:46

+0

当我从活动工作表中启动宏时,我只能从活动工作表中获取复制到workshet xws中的六个单元格(A1:A6)中的相同信息。 – Timbo 2014-09-20 22:42:32

回答

5

你应该声明rng每个ws循环内,如:

Sub exercise() 
    Dim ws As Worksheet 
    Dim rng As Range 

    For Each ws In ActiveWorkbook.Worksheets 
     'Finding last row in column B 
     Set rng = ws.Range("B" & ws.Rows.Count).End(xlUp) '<~~ Moved inside the loop 
     'Don't copy data from xws worksheet 
     If ws.Name <> "xws" Then 
      'Storing first copied data in A1 
      If IsEmpty(Sheets("xws").[A1]) Then 
       rng.Copy Sheets("xws").Range("A" & Rows.Count).End(xlUp) 
      'Storing next copied data below previously filled cell 
      Else 
       rng.Copy Sheets("xws").Range("A" & Rows.Count).End(xlUp).Offset(1, 0) 
      End If 
     End If 
    Next ws 
End Sub 

当你的代码现在,rng将指向ActiveSheet在运行宏的时候,你的代码将然后在代码的每次迭代中复制相同的单元格。

相关问题