我正在将工作表从另一个工作簿导入到当前工作簿。完成导入工作表后,我想关闭其他工作簿。我使用的代码给出错误运行时错误9':下标超出范围。
Sub ImportWorksheet(MyPath As String, wbName As String)
ControlFile = ActiveWorkbook.Name
Workbooks.Open Filename:=MyPath
Sheets(1).Copy After:=Workbooks(ControlFile).Sheets(1)
ActiveSheet.Name = wbName
Workbooks(MyPath).Close SaveChanges:=False
Windows(ControlFile).Activate
End Sub
我也尝试使用
Windows(MyPath).Activate
ActiveWorkbook.Close SaveChanges:=False
但是我得到了同样的错误。
答案 0 :(得分:2)
由于Workbooks对象的Open方法返回一个Workbook对象,因此您可以引用已打开的工作簿:
Sub ImportWorksheet(MyPath As String, wbName As String)
ControlFile = ActiveWorkbook.Name
With Workbooks.Open(Filename:=MyPath)
.Sheets(1).Copy After:=Workbooks(ControlFile).Sheets(1)
.Sheets(2).Name = wbName
.Close SaveChanges:=False
End With
End Sub
答案 1 :(得分:1)
我喜欢分配变量,它消除了任何混乱。
Sub ImportWorksheet(MyPath As String, wbName As String)
Dim Owb As Workbook
Dim Nwb As Workbook
Set Owb = ThisWorkbook
Set Nwb = Workbooks.Open(Filename:=MyPath)
Nwb.Sheets(1).Copy after:=Owb.Sheets(1)
Owb.Sheets(2).Name = wbName
Nwb.Close False
Owb.Activate
End Sub