How to Close Excel Workbook using VBA Code
In this tutorial, we will show you the code for closing the Excel Workbook using VBA. For closing a workbook, you may use the Close method of the Workbook object.
Closing Workbook in VBA
In this tutorial, we will show you the code for closing the Excel Workbook using VBA.
For closing a workbook, you may use the Close method of the Workbook object.
For example,
Workbook(“Workbook_name”).Close
You may also specify whether to save the changes before closing the specified workbook or not.
An example of closing a workbook by saving the changes
The Close method has “SaveChanges” parameter that is used to specify to close the Workbook with or without saving.
The VBA program below closes a workbook after saving the changes. See the sample code below:
Public Sub close_wb() Workbooks("demo_book.XLSX").Close SaveChanges:=True End Sub
So, you may specify the value as True for the SaveChanges parameter of the Close method in order to save the changes made in the Workbook.
The example to close the workbook without saving
Similarly, you may set the “SaveChanges” parameter value as False to close the workbook without saving the changes. A sample program is given below
Code:
Public Sub close_wb() Workbooks("demo_book.XLSX").Close SaveChanges:=False End Sub
Closing the active workbook example
Rather than specifying the name of the Workbook, if you want to close the active workbook, you can do this as follows:
Public Sub close_wb() ActiveWorkbook.Close End Sub
In that case, if changes are made in the active Workbook, Excel will ask to close the Workbook with or without saving the changes.
You may also specify in the code to save the Workbook before closing just like in the above examples:
Public Sub close_wb() ActiveWorkbook.Close SaveChanges:=True End Sub