I am writing a simple macro which will open, save and close an Excel file say myworkbook.xlsx but I am unable to do this. My file myworkbook.xlsx is at location:
C:\Users\Administrator\Desktop\Temp\myworkbook.xlsx
I have written code as
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
The error is:
Run time error 9. Subscript out of range
You only need to specify the path when opening the file:
Sub openSaveClose()
Workbooks.Open "C:\Users\Administrator\Desktop\Temp\files\myworkbook.xlsx"
Workbooks("myworkbook.xlsx").Save
Workbooks("myworkbook.xlsx").Close
End sub
Using an object variable, you can do the following (then no need to use the workbook's name in the Save/Close statements):
Sub openSaveClose()
Dim wb as Workbook
Set wb = Workbooks.Open("C:\Users\Administrator\Desktop\Temp\files\myworkbook.xlsx")
wb.Save
wb.Close
End sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With