2014-09-20 90 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在運行宏的時候,你的代碼將然後在代碼的每次迭代中複製相同的單元格。

相關問題