VBA Code to Open an Excel File: A Complete VBA Guide

VBA & macros · Updated November 20, 2026

To open an existing Excel workbook with VBA, use Workbooks.Open and provide the file’s full path. Paste the complete macro below into a standard VBA module, change the example path to your workbook, and run OpenExcelFile.

Complete VBA code to open a workbook

This macro checks that the workbook exists before trying to open it. If the path is valid, Excel opens the workbook normally; if not, the macro displays a helpful message instead of attempting to open a missing file.

Option Explicit

Sub OpenExcelFile()
    Dim filePath As String
    Dim openedWorkbook As Workbook

    On Error GoTo OpenError

    ' Replace this example with the workbook's full path.
    filePath = "C:\Reports\Sales.xlsx"

    If Len(Dir$(filePath)) = 0 Then
        MsgBox "File not found: " & filePath, vbExclamation
        Exit Sub
    End If

    ' Open the workbook and keep a reference to it.
    Set openedWorkbook = Workbooks.Open(Filename:=filePath)
    openedWorkbook.Activate
    Exit Sub

OpenError:
    MsgBox "Excel could not open the workbook." & vbCrLf & _
           "Details: " & Err.Description, vbExclamation
End Sub

The code belongs in the workbook that will run the macro, not necessarily in the workbook being opened. Save a copy of the workbook containing your VBA before running a macro: macro actions generally cannot be reversed with Ctrl+Z.

What the macro does

Workbooks.Open is Excel’s VBA method for opening an existing workbook. The Filename argument tells Excel which file to open. In the example, filePath is a string variable holding that location, while openedWorkbook refers to the workbook after it has opened. The final Activate line brings that workbook to the foreground.

Option Explicit requires variables to be declared before they are used. This helps catch misspelled variable names when you compile or run the macro. The error handler, beginning at On Error GoTo OpenError, provides a message if Excel encounters an issue such as a file that is locked, damaged, or inaccessible.

The check using Dir$ catches a straightforward missing-file problem first. It does not guarantee that Excel can open the file: the file could still be corrupt, blocked by security settings, or unavailable because a network location is disconnected. That is why the error handler is still useful.

How to add and run the VBA code

  1. Open the workbook that will contain the macro in Excel for Microsoft 365 on Windows.
  2. Press Alt+F11 to open the Visual Basic Editor. If the Developer tab is visible, you can also select Developer > Visual Basic.
  3. In the editor, choose Insert > Module. Paste the complete code into the new module.
  4. Replace C:\Reports\Sales.xlsx with the actual full path and file name, including the extension.
  5. Save the macro-containing workbook as an Excel Macro-Enabled Workbook (.xlsm).
  6. Return to Excel, press Alt+F8, select OpenExcelFile, and choose Run.

The Developer tab may need to be enabled first: in Windows Excel, use File > Options > Customize Ribbon and select Developer. On a Mac, use Tools > Macro > Visual Basic Editor or the Visual Basic command on the Developer tab. Keyboard shortcuts can vary with Mac keyboard and function-key settings; try Option+F11, or Fn+Option+F11 if the function keys control hardware features. Excel for the web does not run VBA macros, so use the desktop Excel application.

Choose the correct file path

The path must identify the file itself, not just its containing folder. For example, C:\Reports\Sales.xlsx includes the drive, folders, file name, and extension. In Windows paths written in VBA strings, a single backslash is correct; you do not need to double the backslashes.

  • Local Windows file: Use a path such as C:\Users\Ava\Documents\Budget.xlsx.
  • Mapped network drive: Use the drive letter and path only if that drive is connected for the person running the macro.
  • Network share: A UNC path commonly begins with two backslashes, for example \\Server\Shared\Budget.xlsx.
  • Mac file: Mac paths typically use a different format, such as /Users/ava/Documents/Budget.xlsx. Use the path format appropriate to the Mac environment and test it in the desktop Mac version of Excel.

Spaces in folder or file names are fine when the path is enclosed in the VBA string’s quotation marks. The extension should match the actual file: common choices include .xlsx, .xlsm, .xlsb, and the older .xls format. If a file is stored in OneDrive or SharePoint, its locally synchronized path may work, but an online sharing link is not necessarily a valid local file path for Workbooks.Open.

Set read-only, link, and password options

The shortest version of the method is Workbooks.Open Filename:=filePath. Excel also supports named arguments that change how the workbook opens. For example, adding ReadOnly:=True opens it in read-only mode, which is useful when the macro only needs to inspect data or when edits should not be saved back to the original file. A read-only setting does not make the file a protected backup; users may still be able to save a separate copy.

Workbooks containing links to other files can prompt about whether to update those links. The UpdateLinks argument can control this behavior: UpdateLinks:=0 tells Excel not to update external references, while UpdateLinks:=3 requests updates. Not updating links can leave linked values unchanged, so select an option based on whether current external data is needed. Do not suppress prompts blindly when the workbook’s results depend on linked files.

For a password-protected workbook, VBA can pass a password using the method’s password arguments, but avoid putting a real password directly in code that other people can inspect. A password written into a macro is not a secure secret-storage method. If you need an editable copy, understand that opening read-only and opening with a password are separate choices.

Let the user select the workbook

If the file can change from one run to another, a file picker is more practical than editing the path in the code each time. This Windows desktop Excel example asks the user to choose one Excel workbook and then opens the selected file.

Option Explicit

Sub ChooseAndOpenExcelFile()
    Dim picker As FileDialog
    Dim selectedPath As String
    Dim openedWorkbook As Workbook

    On Error GoTo OpenError

    Set picker = Application.FileDialog(msoFileDialogFilePicker)

    With picker
        .Title = "Select an Excel workbook"
        .AllowMultiSelect = False
        .Filters.Clear
        .Filters.Add "Excel workbooks", "*.xlsx; *.xlsm; *.xlsb; *.xls"

        If .Show <> -1 Then Exit Sub
        selectedPath = .SelectedItems(1)
    End With

    Set openedWorkbook = Workbooks.Open(Filename:=selectedPath)
    openedWorkbook.Activate
    Exit Sub

OpenError:
    MsgBox "Excel could not open the selected workbook." & vbCrLf & _
           "Details: " & Err.Description, vbExclamation
End Sub

Paste this alternative into a standard module as a separate macro. It uses Excel’s FileDialog object, which is available in desktop Excel; the dialog’s appearance depends on the operating system. Selecting Cancel exits without opening anything. The filter helps users find common Excel file types, but it is not a guarantee that a selected file is valid or safe to open.

Common problems and fixes

  • “File not found” appears: Check every folder name, the drive letter, the extension, and whether the file was moved. Copying the path from File Explorer can help; make sure you copy the file path rather than only the folder location.
  • The macro will not run: Confirm that the code is in a standard module and that the host workbook is saved as .xlsm. Check Excel’s macro notification and security settings rather than enabling all macros globally.
  • The workbook opens read-only: Another user or process may have it open, or the file may be marked read-only or stored in a location where you lack write permission. The macro’s own ReadOnly argument can also request read-only access.
  • Excel shows a link or security prompt: The workbook may contain external links or content that Excel treats cautiously. Review the source and the prompt; do not automatically allow updates or active content if you do not trust the file.
  • The path works on one computer but not another: A local drive letter or user folder is computer-specific. Use a shared location that the intended users can access, or let each user select the file with a picker.

The error message in the sample is intentionally general but includes Err.Description, which can provide a clue. If you modify the macro and add more actions after opening, consider recording the error number and handling cleanup deliberately. Avoid using On Error Resume Next around the whole procedure: it can hide failures and make it appear that a workbook opened when it did not.

Macro security and safe use

VBA code runs with the permissions available to Excel, so a macro should only open files from sources you trust. Excel may display a security warning when a workbook contains macros. Follow your organization’s policies, and do not lower macro security globally just to run a single file. A trusted location or a digitally signed macro may be appropriate in managed environments, but those arrangements should follow the organization’s security guidance.

Keep the macro-containing file separate from the target workbook when that makes the workflow clearer. The code can live in an .xlsm controller workbook and open a target .xlsx workbook; the target does not need to be macro-enabled simply because another workbook opens it. Before running code that might change or save data, make a backup copy. Opening a file alone does not normally alter its contents, but later macro steps could.

When to use another approach

Use VBA when you need a repeatable desktop Excel process, such as opening a known monthly report or prompting a colleague to choose a source workbook. For a one-time task, File > Open is simpler and avoids maintaining a macro. If the goal is to combine and refresh data from files without writing VBA, Power Query may be a better fit; in Windows Excel, it is available from Data > Get Data, with available connectors varying by source and Excel edition.

VBA is not the right route for automating Excel in a browser: Excel for the web cannot run VBA. For web-based automation, Office Scripts may be available in Microsoft 365, subject to the account and organization’s setup. Choose the method based on where the workbook runs, whether the workflow must prompt for a file, and whether users need a macro-enabled desktop file.

Frequently Asked Questions

What is the VBA command to open an Excel file?

Use Workbooks.Open(Filename:=filePath), where filePath contains the workbook’s full path and file name. Put it in a procedure and declare the variables used by that procedure.

Can VBA open a workbook by its file name only?

Yes, if Excel can resolve the name from its current folder or another accessible location, but a full path is more reliable. A file name by itself can fail when the current folder is not the folder you expected.

Can the macro open a workbook without showing it?

Workbooks.Open opens a workbook in the Excel application; it is not a general hidden-file reader. You can manage window visibility in more advanced code, but hiding a workbook can confuse users and should be done only when the workflow requires it.

Does the workbook being opened need to be an XLSM file?

No. The workbook being opened can be an ordinary .xlsx file. The workbook that stores the VBA macro must be saved in a macro-enabled format, such as .xlsm, if you want to retain that code.

Will this VBA code run in Excel for the web?

No. Excel for the web does not run VBA macros. Open the macro-containing workbook in the desktop Excel application; Mac desktop Excel can run VBA too, although paths, shortcuts, and some interface details differ from Windows.

Related

Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.

More in VBA & macros

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.