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.

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.

GetOpenFilename method

  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.

How to Use This Macro

To implement this macro, you need to copy and paste it into the standard module:

  1. Activate the Visual Basic Editor by pressing ALT+F11.
  2. In the Project window, find your project/workbook name and Right-click the project/workbook name in the Project window.
  3. Choose InsertModule.
    Insert Module
  4. Type or paste the code in the newly created module, modifying the GetOpenFilename method parameters(if necessary).
    Type or Paste Macros Code in a Module
  5. Optionally, you can assign the macro to a button (see “How to Assign a Macro to a Button Form Controls or a Sharp”).

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>