The fastest way to point VBA at the workbook the code is running from is ThisWorkbook. It always refers to the file that contains the macro, even after the user switches to another open workbook, so captions, formulas, ranges and saves all land in the right place. The alternative, ActiveWorkbook, refers to whichever file is on top of the screen and changes as soon as anyone clicks another window. If you have ever run a macro and watched it write data into the wrong file, ThisWorkbook is the fix: it is a built-in object, needs no declaration, and works in every desktop version of Excel that supports VBA. The steps below show the common patterns, how to test them safely, and what to do when a reference fails.

What You'll Need

  • A desktop copy of Excel with VBA enabled (Excel for Windows or Excel for Mac). The VBA Editor is not available in Excel for the web or in the mobile apps, so you cannot follow these steps there.
  • Macro security set to allow macros: File > Options > Trust Center > Trust Center Settings > Macro Settings. Labels can vary slightly by version, device and region, so look for a close match. On a Mac, use the Excel menu > Preferences > Security instead.
  • A workbook you can experiment in. Work on a copy until your code is proven, because macros can overwrite or delete data.
  • Basic familiarity with opening the VBA Editor (Alt+F11 on Windows, Option+F11 on a Mac) and inserting a module.

Step-by-Step

  1. Open the VBA Editor and add a module. With your workbook open, press Alt+F11 (Windows) or Option+F11 (Mac). In the Project Explorer, right-click your workbook's VBAProject and choose Insert > Module. Code in a standard module can be called with Alt+F8 from the Excel window, which makes testing simple.
  2. Write your first reference. Type a short procedure that reads a value from the workbook holding the code:

    Sub ShowMyName()
      MsgBox ThisWorkbook.Name
    End Sub

    ThisWorkbook resolves to the file that contains ShowMyName. Nothing is typed into a string, so renaming the file does not break the code.
  3. Run it and confirm the result. Press F5 inside the editor, or Alt+F8 in Excel and pick ShowMyName. The message box should show your file's name, complete with its extension. If it shows a different name, you are running the macro from a personal macro workbook or an add-in (see Common Mistakes).
  4. Target a sheet inside that workbook. Extend the reference to reach the data:

    MsgBox ThisWorkbook.Worksheets("Sheet1").Range("A1").Value

    Use the real tab name in place of Sheet1. To loop through every sheet regardless of names, use ThisWorkbook.Worksheets in a For Each loop instead of writing out names.
  5. Write data back with the same pattern. Put the workbook reference first, then the sheet, then the cell:

    ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = Now

    Because the sheet is qualified, the write happens on that sheet even if the user is looking at another one.
  6. Save explicitly to the right file. ThisWorkbook.Save saves the file containing the code, wherever it lives on disk. Use ThisWorkbook.SaveAs with a full path when you want a new copy, and note that SaveAs changes which file ThisWorkbook points to afterwards. To find the current location at runtime, read ThisWorkbook.FullName or ThisWorkbook.Path (Path is empty for a file that has never been saved).
  7. Prove the difference between the two objects. Open a second workbook, then run:

    MsgBox ThisWorkbook.Name & " / " & ActiveWorkbook.Name

    Switch windows and run it again without touching the code. The first name never changes from the workbook that holds the macro; the second follows whichever window is active. That single test explains most range-copying bugs.
  8. Replace risky references in existing code. Search your module for ActiveWorkbook, ActiveSheet and unqualified Range or Cells calls used for output. Swap the workbook-level ones for ThisWorkbook, and qualify the sheet-level ones with a worksheet object. An unqualified Range("A1") always means the active sheet, which is the usual cause of data landing in the wrong place.
  9. Test with other files open. Close everything, open two unrelated workbooks and activate the one without the macro. Run your procedure again. When it still writes to the correct file you have a portable macro, and it will also work when triggered by a button on any sheet.
  10. Tidy up and keep a backup. Comment what each procedure does, then save the file as a macro-enabled workbook (.xlsm) so the code is retained. Keep a copy of the previous working version before you hand the file to anyone else.

If that did not work

If ThisWorkbook reports the name of your personal macro workbook instead of the file you expected, the code was saved in Personal.xlsb rather than in the workbook. Move the module into the intended file. If you get a "Subscript out of range" error, the sheet name in quotes does not match a tab in the workbook; check spelling including spaces. If a macro that worked before suddenly writes nothing, make sure the target workbook is not protected and that no cell in the range is locked. And if nothing runs at all, check whether macros are disabled by the Trust Center or blocked by a security banner on the file.

Common Mistakes

  • Using ActiveWorkbook for output. It follows the user's clicks. Code that opens a report, copies from it into "the current workbook" and then saves will eventually overwrite the report or save nothing, because the active file keeps changing.
  • Assuming ThisWorkbook is the ActiveWorkbook. They are identical only while the macro's own file is on top. A macro triggered by a button click is usually fine, but code that opens other files is not.
  • Storing the workbook in a variable in a shared module. A Public or module-level workbook variable keeps its value between runs and can hold a stale reference after the file is closed. Read ThisWorkbook fresh inside each procedure.
  • Leaving sheet names unqualified. Sheets("Data").Range("A1") without a workbook prefix searches all open workbooks and raises the "subscript out of range" error if the wrong file is active. Writing ThisWorkbook.Worksheets("Data") removes the ambiguity.
  • Confusing the code name with the file name. The object browser may list the project under a code name such as VBAProject or a custom name; ThisWorkbook.Name returns the saved file name, which is what you usually want in messages and paths.
  • Saving with SaveAs by accident. Calling ThisWorkbook.SaveAs without a full path can drop the file into the current directory. Always pass a complete folder path.

Tips

  • Use ThisWorkbook for anything that touches your own file, and reserve ActiveWorkbook only for deliberate acts on whatever the user has open, such as a one-off format-the-current-sheet helper.
  • Declare worksheet variables with Dim ws As Worksheet and set them once with Set ws = ThisWorkbook.Worksheets("Data"). Short names keep long procedures readable and reduce typos.
  • Show a confirmation using ThisWorkbook.FullName in a debug message box while building new code; it tells you instantly whether the path is what you expect.
  • Turn on Option Explicit at the top of the module so misspelled variables are caught at compile time rather than silently treated as empty values.
  • Keep a small test workbook with two tabs and a second open file beside it. Ten seconds of testing there saves corrupted data later.

Troubleshooting

Start with the simplest checks. If the message box does not appear, confirm the file is saved as .xlsm or .xlsb, that macros are enabled in Trust Center, and that the module is in this workbook's project rather than a separate one. If the macro runs but affects the wrong sheet, add the sheet name to every range reference and retest with another file active. If you get a run-time error about the object or method, look at the line the error highlights: an unqualified Range, a sheet name that no longer exists, or a write to a protected sheet are the usual culprits. Unprotect the sheet (with the password the file owner has) or have the code write elsewhere. If the workbook opens read-only or is locked by another user, Save fails silently or errors; close the other copy first. For files opened from a network share or downloaded from email or the internet, Excel may open them in Protected View, where macros cannot run: choose Enable Editing, and only do so for files you trust. After changing code, compile with Debug > Compile VBAProject before running, then save, close and reopen the workbook once to confirm the code persists and points at the same file.

Frequently Asked Questions

What is the difference between ThisWorkbook and ThisWorkbook in a worksheet module?

Both refer to the same file. A worksheet's own code module also has a shortcut object named after the sheet (for example Sheet1), which refers to that sheet rather than the whole workbook.

Can I use ThisWorkbook in an add-in or personal macro workbook?

Yes, but it then means the add-in or Personal.xlsb, not the file the user is working in. To act on the user's file from an add-in, capture the file you want into a workbook variable and use that variable, and warn that the active file may not be the intended target.

Does ThisWorkbook work in Excel for the web or on a phone?

No. The VBA Editor and VBA macros are desktop-only. In Excel for the web and the mobile apps you would use Office Scripts or formulas instead, and those are different tools with different rules.

Why does ThisWorkbook.Path come back empty?

The file has never been saved, so it has no folder yet. Save it once with a full path and the property returns the folder.

How do I refer to the workbook that was open when the macro started?

Store it in a variable early: Dim wb As Workbook: Set wb = ActiveWorkbook. Every later reference through wb stays on that file even after the user activates another one.

Is it safe to replace every ActiveWorkbook with ThisWorkbook?

Not blindly. It is correct for output into your own file, but wrong when the macro deliberately acts on a file the user just opened or selected. Review each replacement against what the procedure is meant to do.