By utilizing VBA, you can close a specific Excel workbook.
This page introduces how to close a workbook with VBA.
Close Method
To close a workbook with VBA, use the Close method of the Workbook object.
ThisWorkbook.Close
Executing this code closes the workbook that contains the running macro.
If there are no unsaved changes, it closes immediately; if there are, Excel displays a dialog box asking whether to save them.
ThisWorkbook refers to the workbook containing the macro, while ActiveWorkbook refers to the currently active workbook. Use whichever matches the workbook you want to close.
Avoiding Save Confirmation
To close the workbook without the save confirmation, you can pass an argument to the Close method.
Sub CloseWithoutPrompt()
' Close the active workbook without saving changes
ActiveWorkbook.Close SaveChanges:=False
End Sub
In this code, the SaveChanges argument is set to False. This will close the workbook without saving changes, even if there are unsaved changes.
For more details on how to close a workbook without saving, refer to the following page.
To close an Excel workbook without saving in VBA, pass SaveChanges:=False to the Close method. This article covers code examples for the active or a specific workbook, avoiding the confirmation dialog, and safely closing all other workbooks.
Save Changes and Close
Conversely, if you want to save changes before closing the workbook, set the SaveChanges argument to True.
Sub CloseAndSave()
' Save changes and close the active workbook
ActiveWorkbook.Close SaveChanges:=True
End Sub
Executing this code will save the changes and then close the workbook.
Close a Specific Workbook
To close a specific workbook, call the Close method on the workbook object.
Sub CloseSpecificWorkbook()
' Store the specific workbook in a variable
Dim wb As Workbook
Set wb = Workbooks("Example.xlsx")
' Close the specific workbook
wb.Close SaveChanges:=False
End Sub
In this code, the workbook named “Example.xlsx” is closed. Using this method, you can close workbooks that are not active.
If no workbook with that name is open, a run-time error (9: Subscript out of range) occurs. Also, running ThisWorkbook.Close closes the macro’s own workbook, so the code after it will not run.
Arguments of the Close Method
The Close method accepts the following optional arguments.
| Argument | Description |
|---|---|
SaveChanges | True saves and closes, False closes without saving. If omitted, a save confirmation dialog is shown |
Filename | The file name to use when saving changes |
RouteWorkbook | Routing setting when the workbook is circulated |
Summary
By using the Close method in VBA, you can programmatically close Excel workbooks.
By appropriately using the arguments, you can avoid save confirmations, save changes before closing, or target specific workbooks.
In macros that handle multiple workbooks, always close each workbook after processing to avoid wasted memory and accidental edits.