Closing a workbook in VBA

cgclower

New Member
Joined
Feb 28, 2010
Messages
40
OK, I can get VBA to open a workbook, but I can't seem to get it to close the workbook. What am I doing wrong?

Workbooks.Open NewerFile

opens the workbook perfectly, but neither of these work to close it:

Workbook.Close NewerFile

Workbooks(NewerFile).Close

Thanks for the help!
 

Excel Facts

Ambidextrous Undo
Undo last command with Ctrl+Z or Alt+Backspace. If you use the Undo icon in the QAT, open the drop-down arrow to undo up to 100 steps.
to close the workbook you are running this vba from

Thisworkbook.close savechanges:= true
 
Upvote 0
Assuming NewerFile includes the path, you don't use that when closing (or referring to) a workbook.

An easy way is to set an object variable:

Code:
Sub x()
    Dim wkb         As Workbook
 
    Set wkb = Workbooks.Open(NewerFile)
    ' ...
    ' process as desired
    ' ...
    wkb.Close SaveChanges:=True    ' or False, as appropriate
End Sub
 
Upvote 0
filedir = "c:\my documents\"
myfile = "excel file.xls"
workbooks.open filedir & myfile
'do stuff
workbooks(myfile).Close
 
Upvote 0

Forum statistics

Threads
1,223,903
Messages
6,175,284
Members
452,630
Latest member
OdubiYouth

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top