Skip to main content

Excel Macro: Opening a Specific Workbook Chosen by the User

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", _

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

  1. 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.
  2. 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.
  3. 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.
  4. 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.

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:

  1. Activate the Visual Basic Editor by pressing ALT + F11.
  2. Right-click the project/workbook name in the Project Window.
  3. Choose Insert -> Module.
  4. 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.
  5. Click Run button on the Visual Basic Editor toolbar.
  6. For more information, learn this course: Programming with Excel VBA

Leave a comment

Your email address will not be published. Required fields are marked *

Format your code: <pre><code class="language-vba">place your code here</code></pre>