Sometimes you need to allow your users a rapid way to open a Excel Workbook? This macro opens a friendly dialog box, allowing you to browse for and open the Excel Workbook of your choosing.
Macro Code
Sub OpenSpecificFile()
'Step 1: Define a string variable.
Dim SpecificFileName As Variant
'Step 2: GetOpenFilename Method activates dialog box.
SpecificFileName = Application.GetOpenFilename( _
FileFilter:="Excel Workbooks,*.xl*", _
Title:="Choose a Workbook to Open", _
MultiSelect:=False)
'Step 3: If a file was chosen, open it!
If SpecificFileName <> False Then
Workbooks.Open SpecificFileName:=SpecificFileName
End If
End Sub
How This Macro Works
This macro opens the dialog box, allowing the user to browse for and open an Excel file.
- In Step 1, The macro declare a string variant variable that holds the filename that the user chooses. SpecificFileName is the name of our variable.
- In Step 2, we use the GetOpenFilename method to call up a dialog box that allows us to browse and select the file we need.
- The GetOpenFilename method supports a few customizable parameters. The FileFilter parameter allows us to specify the type of file we are looking for. The Title parameter allows us to change the title that appears at the top of the dialog box. The MultiSelect parameter allows us to limit the selection to one file.
- If the user selects a file from the dialog box, the SpecificFileName variable is filled with the name of the file they have chosen. In Step 3, we check for an empty SpecificFileName variable. If the variable is not empty, we use the Open method of the Workbooks object to open the file.
How to Use This Macro
To implement this macro, you need to copy and paste it into the standard module:
- Activate the Visual Basic Editor by pressing
ALT+F11
. - In the Project window, find your project/workbook name and Right-click the project/workbook name in the Project window.
- Choose Insert ➜ Module.
- Type or paste the code in the newly created module, modifying the GetOpenFilename method parameters(if necessary).
- Optionally, you can assign the macro to a button (see “How to Assign a Macro to a Button Form Controls or a Sharp”).