我有许多单独的Excel工作簿,每个工作表都有一个工作表。我需要将其复制到摘要电子表格中。我尝试了以下操作,并将错误9下标超出范围。
workbooks.copy行发生错误。如果我注释掉“after ...”位,它仍然会出现相同的错误,所以它必须是导致错误的workbooks.copy命令,但我无法理解为什么。任何帮助非常感谢。感谢。
Sub test()
On Error GoTo testErr
If Len(Dir("z:\September14\Birmingham.xlsx")) <> 0 Then
If Len(Dir("z:\September14\BirminghamSummary.xlsx")) <> 0 Then
Workbooks("z:\September14\birmingham.xlsx").Sheets(1).Copy , _
after:=Workbooks("z:\September14\BirminghamSummary.xlsx").Sheets(1)
End If
End If
Workbooks.Close
Exit Sub
testErr:
MsgBox Err.Number & " : " & Err.Description
End Sub
答案 0 :(得分:0)
正如@Ron Rosenfeld建议的那样,因为在您尝试复制工作表之前工作簿未打开,所以会触发“下标超出范围”错误。我已经将工作簿定义为这样,以避免提取工作簿名称以便在Workbooks.Close
方法中使用。
Option Explicit
Sub test()
Dim SourceWB As Workbook
Dim DestWB As Workbook
Application.ScreenUpdating - False
On Error GoTo testErr
If Len(Dir("z:\September14\Birmingham.xlsx")) <> 0 Then
Set SourceWB = Workbooks.Open(Filename:="z:\September14\Birmingham.xlsx")
If Len(Dir("z:\September14\BirminghamSummary.xlsx")) <> 0 Then
Set DestWB = Workbooks.Open(Filename:="z:\September14\BirminghamSummary.xlsx")
With SourceWB
.Sheets(1).Copy , after:=DestWB.Sheets(1)
.Close (False)
End With
End If
DestWB.Close (True)
End If
Exit Sub
testErr:
MsgBox Err.Number & " : " & Err.Description
End Sub