我正在写一个简单的宏,它将打开,保存并关闭一个Excel文件,说myworkbook.xlsx,但我无法做到这一点。我的文件myworkbook.xlsx位于:
C:\Users\Administrator\Desktop\Temp\myworkbook.xlsx
我已将代码编写为
Sub openSaveClose()
Workbooks.Open "C:\Users\Administrator\Desktop\Temp\files\myworkbook.xlsx" // This is working fine
Workbooks("C:\Users\Administrator\Desktop\Temp\myworkbook.xlsx").Save
End sub
错误是:
运行时错误9.下标超出范围
答案 0 :(得分:7)
您只需在打开文件时指定路径:
Sub openSaveClose()
Workbooks.Open "C:\Users\Administrator\Desktop\Temp\files\myworkbook.xlsx"
Workbooks("myworkbook.xlsx").Save
Workbooks("myworkbook.xlsx").Close
End sub
使用对象变量,您可以执行以下操作(然后无需在保存/关闭语句中使用工作簿的名称):
Sub openSaveClose()
Dim wb as Workbook
Set wb = Workbooks.Open("C:\Users\Administrator\Desktop\Temp\files\myworkbook.xlsx")
wb.Save
wb.Close
End sub