ThisCalculator

Everyday

VBA Code to Browse for and Open an Excel File

Updated · Standard formula, shown below

VBA Code to Browse for and Open an Excel File

Use Excel’s Application.GetOpenFilename method to let someone browse for a workbook, then open the selected file with Workbooks.Open. This pattern displays a file picker, handles Cancel, and opens the chosen Excel file without requiring a hard-coded path.

Basic VBA code

Put this procedure in a standard VBA module. It opens a dialog filtered for Excel workbooks and opens the selected file when the user chooses one:

Sub BrowseAndOpenExcelFile()
    Dim selectedFile As Variant

    selectedFile = Application.GetOpenFilename( _
        FileFilter:="Excel Files (*.xlsx; *.xlsm; *.xls; *.xlsb)," & _
                   "*.xlsx; *.xlsm; *.xls; *.xlsb", _
        Title:="Select an Excel workbook")

    If selectedFile = False Then Exit Sub

    Workbooks.Open Filename:=CStr(selectedFile)
End Sub

The first call displays Excel’s standard Open dialog but does not open the workbook. It returns the chosen path, or the Boolean value False if the person cancels. The check must happen before passing the result to Workbooks.Open; otherwise, cancellation can cause a type or path error.

How to add and run the macro

  1. Open the workbook that should contain the macro.
  2. Open the Visual Basic Editor with Alt+F11 on Windows. On Mac, use Excel’s Visual Basic Editor command; the shortcut can differ by keyboard and settings.
  3. In the editor, choose Insert > Module.
  4. Paste the code into the module, then return to Excel.
  5. Run BrowseAndOpenExcelFile from the Macros dialog or the Visual Basic Editor. If the workbook is macro-enabled, save it as an Excel Macro-Enabled Workbook (.xlsm).

The macro can also be assigned to a worksheet button: insert a form control button, then assign the procedure. The button is simply a convenient way to run the same code; it does not change how the dialog or workbook opening works.

What the key lines do

  • Application.GetOpenFilename asks the user to select a file and returns its full path. It does not itself open or modify that file.
  • FileFilter supplies a description and a matching pattern. The example includes common Excel workbook formats: .xlsx, .xlsm, .xls, and .xlsb.
  • Title sets the dialog’s heading so the user knows what to choose.
  • selectedFile is declared as a Variant because the result can be either a path or Boolean False.
  • Workbooks.Open opens the selected workbook in the current Excel application.

A common misconception is that GetOpenFilename opens the file automatically. It only returns a selection. The separate Workbooks.Open call performs the opening.

Choose a starting folder or allow multiple files

To start the dialog in a particular folder, set Excel’s current directory immediately before calling GetOpenFilename:

ChDrive "C"
ChDir "C:\Users\Public\Documents"

These commands change Excel’s current drive and folder, which can affect other file operations in the same Excel session. The folder must exist and be accessible. A shared or network location can be used if the user has permission and the path is available.

To permit multiple selections, add MultiSelect:=True to the GetOpenFilename call. The result is then an array of paths when files are selected, rather than one path, so the opening code must loop through the array. For example, the essential pattern is:

Dim files As Variant
Dim i As Long

files = Application.GetOpenFilename( _
    FileFilter:="Excel Files (*.xlsx; *.xlsm),*.xlsx;*.xlsm", _
    MultiSelect:=True)

If VarType(files) = vbBoolean Then Exit Sub

For i = LBound(files) To UBound(files)
    Workbooks.Open Filename:=CStr(files(i))
Next i

With multiple selection enabled, checking for cancellation before treating the result as an array is important. The Boolean test handles the Cancel result.

Opening safely and handling problems

Opening a workbook can run its macros if Excel’s security settings allow them. Do not automatically open files from unknown or untrusted sources. If the file may contain macros, follow your organization’s security guidance and review Excel’s prompts rather than trying to bypass them.

For an automated workflow, you may want to prevent macros in the selected workbook from running during the open operation. Excel’s Workbooks.Open method accepts options such as UpdateLinks and ReadOnly; macro security is controlled separately by Excel’s security settings and the AutomationSecurity property. Changing application-wide security settings requires care: save the existing setting and restore it even if opening fails. Do not treat a file picker as a security check; it only lets a user choose a path.

If the macro does not work, check these likely causes:

  • Cancel causes an error: confirm the code tests whether the result is False before opening it.
  • The file type is missing: add its extension to both the filter description and pattern. A filter controls what is shown; it is not a guarantee that every matching file is a valid workbook.
  • Excel says the path cannot be found: check that the file still exists and that the user can access the folder, especially for removable drives or network locations.
  • The macro will not run: confirm the file is saved in a macro-enabled format and that Excel permits the macro under the applicable security settings.
  • The wrong workbook opens: inspect the returned full path and consider whether another copy with the same filename is in a different folder.

Alternatives and useful options

If the user should choose a file and immediately open it in the normal Excel interface, Application.Dialogs(xlDialogOpen).Show is another option. It uses Excel’s built-in Open dialog behavior, but offers less direct control over the selected path in VBA than GetOpenFilename.

If the path is fixed and no browsing is needed, call Workbooks.Open directly with a known path. This is appropriate for repeatable tasks, but a hard-coded path can break when folders, usernames, or drive mappings change. For a user-facing macro, a picker is usually more flexible.

You can also open a workbook read-only by using Workbooks.Open Filename:=CStr(selectedFile), ReadOnly:=True. This is useful when the macro only needs to inspect data and should not invite accidental edits. It does not prevent all possible changes to the file by other processes, and it does not replace sound file-handling practices.

Frequently Asked Questions

Does GetOpenFilename open the workbook?
No. It displays the picker and returns the selected path. Use Workbooks.Open afterward to open the workbook.

How do I handle Cancel in the file dialog?
Store the result in a Variant and test whether it equals False before using it as a path. The basic example exits the macro when the user cancels.

Can I make the dialog show only Excel files?
Use the FileFilter argument with patterns for the extensions you want, such as *.xlsx;*.xlsm. Users may still be able to change dialog filters depending on the dialog and Excel environment.

How do I open the selected file read-only?
Add ReadOnly:=True to the Workbooks.Open call. For example: Workbooks.Open Filename:=CStr(selectedFile), ReadOnly:=True.

Can the macro open more than one selected workbook?
Yes. Set MultiSelect:=True, check for the Boolean Cancel result, and loop over the returned array of file paths, opening each one.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.