我正在尝试将一系列工作表(根据用户首选项动态创建)中的数据复制到位于末尾的主工作表中。但是,在第一个循环之后,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 :(得分: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