Close a Workbook

Maintained on

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.

Close
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.

Close
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.

Close Workbook Without Saving
To close an Excel workbook without saving in VBA, pass SaveChanges:=False to the Close method. This article covers code

Save Changes and Close

Conversely, if you want to save changes before closing the workbook, set the SaveChanges argument to True.

Save
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.

Close
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.

Arguments of the Close Method

The Close method accepts the following optional arguments.

ArgumentDescription
SaveChangesTrue saves and closes, False closes without saving. If omitted, a save confirmation dialog is shown
FilenameThe file name to use when saving changes
RouteWorkbookRouting 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.

Using the Close method expands the range of workbooks you can handle with VBA.

#VBA