2017-07-06 30 views
0

我試圖將數據從一系列工作表(基於用戶首選項動態創建)複製到位於末尾的主工作表中。但是,在第一次循環之後,Excel會遇到面向對象的錯誤(1004)。循環問題 - 無法移動過去的第一次迭代

Dim MacroWorkbook As Workbook 
Set MacroWorkbook = Thisworkbook 

Dim NumSheets As Integer 
Dim DataSheets As Integer 
Dim LCounter As Single 

'Count the number of sheets 
NumSheets = MacroWorkbook.Worksheets.Count 
'Count the number of sheets minus the mastersheet (located at the end). 
DataSheets = NumSheets - 1 

'As long as the counter is less than the number of total sheets (i.e. master sheet) 
Do While LCounter < NumSheets 
    LCounter = LCounter + 1 
    MacroWorkbook.Sheets(LCounter).Range(Range("A2"), Range("AU5001")).Copy 
    MacroWorkbook.Sheets(NumSheets).Range("A1").End(xlDown).PasteSpecial Paste:=xlPasteValues 
Loop 

1)爲什麼不能在第二個循環中執行Excel?

2)錯誤與使用複製/粘貼有關嗎?有沒有更高效/更笨重的方法?

回答

0

可能是因爲您需要爲所有範圍添加圖紙引用,但是您的代碼在您每次粘貼時似乎都會覆蓋?而你的Do行應該引用DataSheets,而不是我認爲的NumSheets。

Dim MacroWorkbook As Workbook 
Set MacroWorkbook = ThisWorkbook 

Dim NumSheets As Integer 
Dim DataSheets As Integer 
Dim LCounter As Single 

'Count the number of sheets 
NumSheets = MacroWorkbook.Worksheets.Count 
'Count the number of sheets minus the mastersheet (located at the end). 
DataSheets = NumSheets - 1 

'As long as the counter is less than the number of total sheets (i.e. master sheet) 
Do While LCounter < NumSheets 
    LCounter = LCounter + 1 
    With MacroWorkbook 
     .Sheets(LCounter).Range(.Sheets(LCounter).Range("A2"), .Sheets(LCounter).Range("AU5000")).Copy 
     .Sheets(NumSheets).Range("A2").PasteSpecial Paste:=xlPasteValues 
    End With 
Loop 
+0

你說得對,數據會覆蓋自己。這只是一些佔位符代碼,它已在OP中更新。雖然你是代碼作品。 –

相關問題