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.
Opening a Specific Workbook Chosen by the User
'------------------ Modules ------------------ 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 Filename:=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
Most VBA code should be placed in Standard Modules unless specified.
If you see a comment
'------------------ Modules------------------ in the code header that means put the code in a Standard Module. For more information, learn this course: Where should I put the Excel VBA code?
The following steps teach you how to put VBA code into a Standard Module:
- Activate the Visual Basic Editor by pressing ALT + F11.
- Right-click the project/workbook name in the Project Window.
- Choose Insert -> Module.
- Type or paste the code in the newly created module. You will probably need to change the sheet name, the range address, and the save location.
- Click Run button on the Visual Basic Editor toolbar.
- For more information, learn this course: Programming with Excel VBA