Close and Open in Excel VBA

 

The Close method in Excel VBA is used to close workbooks. The Open method allows you to open existing workbooks.

Remember, the Workbooks collection contains all the Workbook objects that are currently open.

Place a command button on your worksheet and add the following code lines:

1. The code line below closes close-open.xlsm.

Workbooks("close-open.xlsm").Close

2. The code line below closes the first opened/created workbook.

Workbooks(1).Close

3. The code line below closes the active workbook.

ActiveWorkbook.Close

4. The code line below closes all workbooks that are currently open.

Workbooks.Close

5. The code line below opens sales.xlsx.

Workbooks.Open ("sales.xlsx")

Note: you can only open sales.xlsx without specifying the file's path if it's stored in your default file location. To change the default file location, on the File tab, click Options, Save.

6. You can also use the GetOpenFilename method of the Application object to display the standard Open dialog box.

Dim MyFile As String
MyFile = Application.GetOpenFilename()

7. Select a file and click Open.

GetOpenFilename Method

Note: GetOpenFilename doesn't actually open the file.

8. Next, you can open the workbook as usual.

Workbooks.Open (MyFile)

If you're new here, welcome to Excel Easy! Join over 1 million monthly Excel learners. You can find popular courses here: Data Analysis in Excel and Excel VBA.