2017-07-06 58 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中更新。虽然你是代码作品。 –