打开,保存并关闭任何文件

时间:2015-11-08 17:25:11

标签: excel vba excel-vba

我正在写一个简单的宏,它将打开,保存并关闭一个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.下标超出范围

1 个答案:

答案 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