You can find and replace text anywhere in a workbook with a few lines of VBA: open the Visual Basic Editor, create a module, and call Replace or Cells.Replace. The simplest version replaces text in a single range, while a loop lets you walk every sheet, every column or an entire workbook. This guide covers both, plus how to make replacements safe and undoable.

What You'll Need

  • Microsoft Excel on Windows or Mac with macros enabled (VBA is built in; no add-in required).
  • A workbook saved as .xlsm (macro-enabled) or a personal macro workbook if you want the code to persist.
  • The Visual Basic Editor (VBE), opened with Alt+F11 on Windows or Fn+Option+F11 on most Macs, or via the Developer tab.
  • If the Developer tab is hidden: File > Options > Customize Ribbon, tick Developer in the right-hand list, click OK. On older Mac builds the path is Excel > Preferences > Ribbon & Toolbar. Labels vary slightly by version and region.
  • A backup copy of the file before running anything that changes many cells.

Step-by-Step

  1. Open the editor. Press Alt+F11 (Windows) or Fn+Option+F11 (Mac). The VBE opens in a separate window.
  2. Insert a module. In the VBE menu choose Insert > Module. A blank code window appears. Do not paste code into the sheet's own code module unless you want it to fire on an event like Worksheet_Change.
  3. Write the basic single-range replace. This changes every match in A1:A100, ignoring case by default:
    Sub SimpleReplace()
        Range("A1:A100").Replace _
            What:="old text", _
            Replacement:="new text", _
            LookAt:=xlPart
    End Sub
    LookAt:=xlPart matches the phrase anywhere inside a cell; use xlWhole to match the entire cell contents only.
  4. Run it. Click inside the procedure and press F5, or use Run > Run Sub/UserForm. Alternatively add a button from the Developer tab and assign the macro to it. If Excel asks about macros, choose Enable Content only for files you trust.
  5. Make it case-sensitive if needed. Add MatchCase:=True. Without it, "Total" and "total" both match, which is usually what people want but can surprise you when abbreviations and proper nouns are mixed in one column.
  6. Replace across an entire sheet. Swap the range for Cells : Sub SheetReplace() Cells.Replace What:="N/A", Replacement:="", _ LookAt:=xlPart, SearchOrder:=xlByRows End Sub An empty Replacement
  7. Loop over every worksheet. This is the version worth keeping, because most replacements need to cover the whole workbook:
    Sub WorkbookReplace()
        Dim ws As Worksheet
        For Each ws In ThisWorkbook.Worksheets
            ws.Cells.Replace What:="OldCo", Replacement:="NewCo", _
                LookAt:=xlPart, MatchCase:=False
        Next ws
    End Sub
    Replace ThisWorkbook with ActiveWorkbook if you want the macro to work on whatever file is open at the time.
  8. Handle values versus formulas. Cells.Replace searches formulas by default. If replacing words inside text strings is fine but replacing function names would break things, restrict the search: Cells.SpecialCells(xlCellTypeConstants).Replace ... touches only typed values, while xlCellTypeFormulas touches only formulas. Using LookIn:=xlValues as an argument to Find gives value-level matching, but be aware it still returns cells whose formula produced the match.
  9. Reset the find settings afterwards. VBA's Replace method leaves the workbook's Find and Replace dialog settings changed. Add Application.FindFormat.Clear and Application.ReplaceFormat.Clear at the end of the macro so the next manual Ctrl+H behaves normally.
  10. Turn off screen updating for speed. For large workbooks, wrap the loop:
    Application.ScreenUpdating = False
    ' ... your loop ...
    Application.ScreenUpdating = True
    This cuts flicker and run time on sheets with thousands of rows. Always restore the setting, or Excel can appear frozen.
  11. Save and test on a copy. Press Ctrl+S. Keep the file as .xlsm so the code survives closing. Run once on a duplicate workbook and compare a few cells before trusting it on the real one.

Common Mistakes

  • Using wildcard characters literally. In Replace, the characters *, ? and ~ are wildcards. Searching for A* matches everything beginning with A. Escape a literal asterisk as ~*, a literal question mark as ~? and a literal tilde as ~~.
  • Forgetting LookAt. The default differs between contexts. Set xlPart or xlWhole explicitly so the macro does not depend on whatever the user last selected in the dialog.
  • Assuming an error is raised when nothing matches. It is not: Replace simply does nothing and the macro continues. Check the return value if you need to report a count.
    Dim hits As Long
    hits = Cells.Replace(What:="X", Replacement:="Y")
    MsgBox hits & " cells changed"
    The return value is True if anything changed, False otherwise, not a number.
  • Pasting into the sheet code module. Code in Sheet1 only runs when a workbook event fires; ordinary macros belong in a standard module.
  • Replacing inside formulas carelessly. Rewriting "SUM" or a cell reference breaks formulas silently. Test with constants only first.
  • No undo. VBA changes cannot be undone with Ctrl+Z. Take a backup or run the macro on a copy.

Tips

  • Store recurring macros in your Personal Macro Workbook so they are available in every session. Record a throwaway macro with Developer > Record Macro, choose the personal workbook in the store location, then edit the generated code.
  • Use a variable instead of hard-coded strings so you can change the search text in one place:
    Const OLD_TXT As String = "OldCo"
  • Write a two-way cleanup routine: replace the placeholder with a marker first, then the marker with the final text, so a replacement never matches its own output in the same pass.
  • Log changes. Write old and new values to a spare sheet as you go, which makes it easy to audit what a bulk replacement touched.
  • Restrict scope deliberately: use Range("A1:B500") or a named range rather than Cells when only some columns should change.
  • Keep macros that touch many cells behind a confirmation prompt: If MsgBox("Replace all?", vbYesNo) = vbYes Then ....

Troubleshooting

Nothing happens. Check the macro actually runs (the status bar shows "Ready" again with no error), and confirm the text matches exactly, including hidden trailing spaces. Copy a cell value into the Immediate window (Ctrl+G) with ?"[" & Range("A1").Value & "]" to see stray spaces.

Numbers are not being replaced. A cell holding the number 2024 is not the text "2024". Either convert with Text functions or use Value comparison, and remember LookAt:=xlWhole on a numeric cell compares numbers, not strings.

Macro is greyed out or blocked. Check File > Options > Trust Center > Trust Center Settings > Macro Settings and the file's location (files from the internet open in Protected View; click Enable Editing first). On Mac, confirm the file is .xlsm and macros are enabled in Excel's security preferences.

Replacement hit the wrong cells. Restore from your backup, then narrow the range and add MatchCase:=True or LookAt:=xlWhole before re-running.

Find and Replace dialog now behaves oddly. The macro left its format settings behind. Run Application.FindFormat.Clear and Application.ReplaceFormat.Clear, or close and reopen the workbook.

Frequently Asked Questions

Can VBA replace text across multiple workbooks at once?

Loop over Workbooks and then Worksheets inside each, applying Cells.Replace per sheet. Only open workbooks are reachable; closed files must be opened first.

Does Replace work on cell comments and shapes?

No. It works on cell contents. Comments have their own .Text property, and text boxes and chart titles need to be addressed individually through the shape's TextFrame.

Why is my replacement faster with ScreenUpdating off?

Excel redraws the sheet after every change. Disabling redraw batches the work into one paint at the end, which matters most on large sheets.

Can I match only whole words?

Not directly. LookAt:=xlWhole matches the entire cell, not whole words inside a sentence. For word-level matching, loop with InStr and string functions, or use a regular expression via VBScript.RegExp.

Will the macro change my formatting?

Only the cell value changes. Fonts, fills, borders and number formats stay as they are, unless the replaced string made Excel re-evaluate a formula's result type.

Is there an undo option after running it?

No. VBA does not register on Excel's undo stack. Keep a backup copy or a change log sheet if you need to roll back.