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 will close the workbook without any confirmation.

However, if there are unsaved changes in the workbook, a dialog box will appear asking whether to save the changes.

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
If you only need to reference a file, it is sufficient to simply close it without saving. Unnecessarily saving the file

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.

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