Excel – 试图通过工作簿循环时出错

祝您有个好日子,当我试图循环打开所有打开的工作簿以复制并粘贴到主工作簿时,我收到错误。 对于我的生活,我无法弄清楚如何纠正,你们有没有人可以帮忙?

Sub LoopCopyPaste() Dim wb As Workbook Dim Lastrow As Long For Each wb In Application.Workbooks If wb.Name <> "MasterDatabase.xlsx" & "MacrosExcelFile.xls" Then Lastrow = wb.Worksheets(1).Cells(Rows.Count, 2).End(xlUp).Row wb.Worksheets(1).Range("B7:J" & Lastrow).Copy '' Windows("MasterDatabase.xlsx").Activate Range("B" & Rows.Count).End(xlUp).Offset(1).Select ActiveSheet.Paste End If Next wb End Sub 

错误是“1004,应用程序定义或对象定义的错误”,它指向“Lastrow = wb.Worksheets(1).Cells(Rows.Count,2).End(xlUp).Row”句子。 我能做些什么来解决这个问题? 提前致谢。

 If wb.Name <> "MasterDatabase.xlsx" And wb.Name <> "MacrosExcelFile.xls" Then 

尝试改变这一点。 当我testing一下,我会更新这个答案。

我能够用下面的一段代码重现这个问题

 Sub Tester() Dim lastrow As Long code here Dim lastrow As Long lastrow = ActiveWorkbook.Worksheets(1).Cells(Rows.Count, 2).End(xlUp).Row End Sub 

在我的情况下,我插入了一个图表,并在运行代码时处于活动状态。 也许这有帮助。

我能够解决这个“我的”问题

 Sub TestB() Dim wkb As Workbook Dim wks As Worksheet Dim lastrow As Long Set wkb = ActiveWorkbook Set wks = wkb.Worksheets(1) lastrow = wks.Cells(wks.Rows.Count, 3).End(xlUp).Row End Sub 

SalvadorVayshun是正确的

 If wb.Name <> "MasterDatabase.xlsx" And wb.Name <> "MacrosExcelFile.xls" Then 

这是我将如何重构代码

 Sub LoopCopyPaste() Application.ScreenUpdating = False Dim wb As Workbook Dim Lastrow As Long For Each wb In Application.Workbooks If wb.Name <> "MasterDatabase.xlsx" And wb.Name <> "MacrosExcelFile.xls" Then With wb.Worksheets(1) .Range("B7:J7", .Cells(.Rows.Count, 2).End(xlUp)).Copy End With With Workbooks("MasterDatabase.xlsx").Worksheets(1) .Range("B" & .Rows.Count).End(xlUp).Offset(1).PasteSpecial End With End If Next wb Application.ScreenUpdating = True End Sub 

仅值

 Sub LoopCopyPaste() Application.ScreenUpdating = False Dim wb As Workbook Dim Lastrow As Long Dim Data For Each wb In Application.Workbooks If wb.Name <> "MasterDatabase.xlsx" And wb.Name <> "MacrosExcelFile.xls" Then With wb.Worksheets(1) Data = .Range("B7:J7", .Cells(.Rows.Count, 2).End(xlUp)).Value End With With Workbooks("MasterDatabase.xlsx").Worksheets(1) .Range("B" & .Rows.Count).End(xlUp).Offset(1).Resize(UBound(Data, 1), UBound(Data, 2)).Value = Data End With End If Next wb Application.ScreenUpdating = True End Sub 

值和公式

 Sub LoopCopyPaste() Application.ScreenUpdating = False Dim wb As Workbook Dim Lastrow As Long Dim Data For Each wb In Application.Workbooks If wb.Name <> "MasterDatabase.xlsx" And wb.Name <> "MacrosExcelFile.xls" Then With wb.Worksheets(1) Data = .Range("B7:J7", .Cells(.Rows.Count, 2).End(xlUp)).Formula End With With Workbooks("MasterDatabase.xlsx").Worksheets(1) .Range("B" & .Rows.Count).End(xlUp).Offset(1).Resize(UBound(Data, 1), UBound(Data, 2)).Formula = Data End With End If Next wb Application.ScreenUpdating = True End Sub