Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel VBA: Replace Part of a String (Step-by-Step)

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To replace part of a string in Excel VBA, use the built-in Replace function: Replace(expression, find, replace) returns a new string with every occurrence of find swapped for replace. For example, Replace("AB-1234", "AB", "XY") returns XY-1234. If you want to change the text in a cell, write the result back to that cell, because Replace never edits the original string or cell in place. Everything below builds on that one line, including how to limit the number of replacements, how to ignore case, and how to loop over a whole column safely.

What You'll Need

  • Excel on Windows or Mac with macros enabled (the VBA editor is included in every desktop edition; Excel for the web does not run VBA).
  • Access to the Developer tab, or the ability to open the VBA editor with Alt+F11 (Windows) or Option+F11 (Mac). If the Developer tab is hidden, right-click the ribbon and choose Customize the Ribbon, then tick Developer.
  • A workbook saved as .xlsm (macro-enabled) if you want to keep your code. Saving as .xlsx strips the macros.
  • A backup copy of your data before you run a bulk find-and-replace, since a macro cannot be undone with Ctrl+Z after it finishes.

Step-by-Step

  1. Open the VBA editor. Press Alt+F11 on Windows or Option+F11 on Mac. The editor opens in its own window. Menu labels can differ slightly by version and platform, but the layout is the same.
  2. Insert a module. In the editor, choose Insert > Module. A blank code pane appears. Code placed in a standard module is available to the whole workbook.
  3. Write a simple test procedure. Paste this in and press F5 to run it:
    Sub SimpleReplace()
        Dim original As String
        Dim result As String
        original = "Order AB-1234 shipped"
        result = Replace(original, "AB", "XY")
        MsgBox result
    End Sub
    The message box shows Order XY-1234 shipped. Note that original is unchanged; only result holds the new text.
  4. Understand the full syntax. The signature is Replace(expression, find, replace, [start], [count], [compare]). start is the character position to begin at (default 1). count is how many replacements to make; -1 or omitted means all. compare is vbBinaryCompare (default, case-sensitive) or vbTextCompare (case-insensitive).
  5. Make the match case-insensitive. Add the compare argument: Replace(original, "ab", "XY", 1, -1, vbTextCompare). This now matches AB, Ab, aB and ab. Without it, only the exact case matches, which is the single most common cause of "it did nothing".
  6. Replace only the first occurrence. Set count to 1: Replace(original, "-", "_", 1, 1). This is useful when a delimiter appears several times but you only want the first one changed.
  7. Replace text inside a cell. Use the cell's .Value on both sides of the assignment:
    Sub ReplaceInCell()
        With ThisWorkbook.Worksheets("Sheet1").Range("A1")
            .Value = Replace(.Value, "Old", "New", 1, -1, vbTextCompare)
        End With
    End Sub
    Reading and writing the same cell in one statement is safe; the value is read first, then written back.
  8. Loop over a whole column. Work from the last used row upward so deletions or blanks do not shift rows you have not processed yet:
    Sub ReplaceInColumn()
        Dim ws As Worksheet
        Dim lastRow As Long, i As Long
        Set ws = ThisWorkbook.Worksheets("Sheet1")
        lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
        For i = lastRow To 1 Step -1
            If Not IsError(ws.Cells(i, "A").Value) Then
                ws.Cells(i, "A").Value = Replace(CStr(ws.Cells(i, "A").Value), "Old", "New", 1, -1, vbTextCompare)
            End If
        Next i
    End Sub
  9. Guard against errors and blanks. The IsError check skips cells showing #N/A or similar. CStr converts numbers and dates to text so Replace does not fail; without it, a numeric cell raises a type mismatch.
  10. Speed it up for large ranges. Turn off screen updating and calculation while the loop runs, then turn them back on: Application.ScreenUpdating = False before the loop and Application.ScreenUpdating = True after. Add Application.Calculation = xlCalculationManual and restore it to xlCalculationAutomatic afterwards. Always restore these settings, even if an error occurs, or Excel stays sluggish until restarted.
  11. Save and test on a copy. Save the workbook as .xlsm, run the macro on a duplicate sheet first, and compare results before trusting it on live data.

Common Mistakes

  • Expecting the original to change. Replace returns a new string. If you write Replace(cell.Value, "a", "b") without assigning the result, nothing happens.
  • Forgetting the compare argument. The default is case-sensitive, so "old" will not match "Old". Pass vbTextCompare when case should not matter.
  • Passing a cell object instead of its value. Replace(Range("A1"), ...) fails or misbehaves; use Range("A1").Value.
  • Type mismatch on numbers. Numeric or error values need CStr and an IsError check.
  • Replacing in a forward loop while deleting rows. Row numbers shift and you skip data. Loop backwards or collect rows first.
  • Confusing VBA Replace with Excel's Find and Replace dialog. The dialog has its own options (Match case, Match entire cell contents) and is not controlled by your code unless you call it explicitly.

Tips

  • Use a placeholder when swapping two strings, or one replacement will overwrite the other. To swap "cat" and "dog", first replace "cat" with a token like ###, then "dog" with "cat", then ### with "dog".
  • Empty the replace argument ("") to delete the matched text entirely.
  • Test your pattern on a single cell with MsgBox before running it across thousands of rows.
  • Keep a copy of the original value in a spare column if the change is hard to reverse; macros do not participate in the undo stack.
  • For pattern-based changes (digits, spaces, punctuation), VBA's Replace only matches literal text. Use RegExp from the Microsoft VBScript Regular Expressions reference when you need wildcards.

Troubleshooting

If nothing changes, confirm you assigned the result back to the cell or variable, and check the case setting. If you get a "Sub or Function not defined" error, you likely typed replace as a variable name or placed the code in the wrong module; rename the variable and move the procedure to a standard module. If you get a type mismatch, wrap the source in CStr and skip error cells. If the macro runs but Excel feels slow afterwards, screen updating or calculation was left off; set both back to their defaults or close and reopen the workbook. If the macro is missing after reopening, the file was saved as .xlsx; save as .xlsm instead. If a security warning blocks macros, enable them for that file through the Trust Center, and only do so for files you created or trust.

Frequently Asked Questions

Does VBA Replace change the original string?

No. It returns a new string. Assign the result to a variable or back to the cell to keep the change.

How do I replace only the first match?

Set the count argument to 1: Replace(text, find, repl, 1, 1).

How do I make the replacement case-insensitive?

Pass vbTextCompare as the sixth argument. The default, vbBinaryCompare, is case-sensitive.

Can I replace text across multiple sheets at once?

Not with a single call. Loop through the Worksheets collection and run the replacement on each sheet's used range.

Why does Replace fail on a cell containing a number?

Replace expects a string. Convert with CStr first, and check for error values with IsError.

Can I use wildcards like * in VBA Replace?

No. Replace matches literal text only. For patterns, use a regular expression object instead.