Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open, save and close any file

Tags:

excel

vba

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

like image 934
Shrikant Salunke Avatar asked Dec 29 '25 01:12

Shrikant Salunke


1 Answers

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
like image 141
David Avatar answered Dec 31 '25 19:12

David



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!