Smart Systems for Home

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

Excel VBA: Replace Character in String (Step-by-Step)

· 5 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 a character in a string with Excel VBA, use the built-in Replace function. The shortest working form is Replace(expression, find, replace), for example Replace("Hello World", "o", "0") returns Hell0 W0rld. You can run this from the Immediate window, from a recorded macro, or from a full subroutine that writes the result back to a cell. The steps below cover the safe, repeatable way to do it, including the optional arguments that control case sensitivity and how many replacements are made.

What You'll Need

  • Excel on Windows or Mac with the Developer tab enabled (File > Options > Customize Ribbon > check Developer, or Excel > Preferences > Ribbon & Toolbar on Mac).
  • A workbook saved as .xlsm (macro-enabled) if you plan to keep the code.
  • Basic familiarity with opening the VBA editor (Alt+F11 on Windows, Option+F11 on Mac).
  • A backup copy of any sheet you will modify, because VBA writes changes directly and Ctrl+Z does not undo a macro.

Step-by-Step

  1. Open the VBA editor. Press Alt+F11 (Windows) or Option+F11 (Mac). Menu labels and window names can differ slightly by Excel version and region, so if a label is not exactly as described, look for the closest match.
  2. Insert a module. In the editor, choose Insert > Module. Code placed in a standard module is available to every sheet in the workbook.
  3. Write the simplest replacement. Type a short test procedure:
    Sub SimpleReplace()
        Dim s As String
        s = "A-B-C"
        s = Replace(s, "-", "/")
        MsgBox s
    End Sub
    This replaces every hyphen with a forward slash and shows A/B/C.
  4. Run it. Place the cursor inside the procedure and press F5, or use Run > Run Sub/UserForm. If a dialog asks which macro to run, pick SimpleReplace.
  5. Replace only the first occurrence. Add the optional Count argument: Replace(s, "-", "/", 1, 1). The fourth argument is Start (where to begin, 1-based) and the fifth is Count (how many replacements; -1 means all).
  6. Control case sensitivity. The sixth argument is Compare. Use vbBinaryCompare for case-sensitive matching or vbTextCompare for case-insensitive. Example: Replace("Apple", "a", "x", 1, -1, vbTextCompare) returns xpple.
  7. Apply it to a cell. Read the value, replace, then write it back:
    Sub ReplaceInCell()
        Dim r As Range
        For Each r In Range("A1:A10")
            r.Value = Replace(r.Value, " ", "_")
        Next r
    End Sub
    This turns spaces into underscores in A1:A10. Adjust the range to your data.
  8. Handle empty cells. Before replacing, guard with If Len(r.Value) > 0 Then so blank cells are skipped and stay blank.
  9. Test on a copy. Run the macro on a duplicate sheet first. If the result is wrong, close without saving and correct the code rather than trying to undo.
  10. Save as macro-enabled. Use File > Save As and choose Excel Macro-Enabled Workbook (.xlsm). Saving as .xlsx strips the code.

Common Mistakes

  • Forgetting that Replace returns a new string. Replace(s, "a", "b") does not change s unless you assign it back: s = Replace(s, "a", "b").
  • Confusing Start and Count. The fourth argument is where to start, the fifth is how many to replace. Swapping them produces surprising partial results.
  • Assuming case-insensitive matching. The default is binary (case-sensitive). Use vbTextCompare when case should be ignored.
  • Replacing inside formulas. Writing to a cell that contains a formula overwrites the formula. Target value cells, or write results to a separate column.
  • Using a wildcard. Replace treats * and ? as literal characters, not wildcards. If you need pattern matching, use Like or a RegExp object instead.
  • Running on the wrong sheet. Unqualified Range("A1") refers to the active sheet. Qualify with Worksheets("Data").Range("A1") to be safe.

Tips

  • Use a constant for the search text so you can change it in one place: Const FindText As String = "-".
  • To remove a character entirely, replace it with an empty string: Replace(s, ",", "").
  • Chain replacements for multiple characters: s = Replace(Replace(s, "-", ""), " ", "").
  • Use Trim after replacing spaces with underscores if leading or trailing spaces should not become underscores.
  • For large ranges, read into a Variant array, process in memory, then write back in one step. This is much faster than cell-by-cell loops.
  • Test with Debug.Print in the Immediate window (Ctrl+G) before writing to cells.

Troubleshooting

  • Compile error: Expected: = — You likely wrote Replace s, "a", "b" as a statement. Use the function form with assignment.
  • Nothing changes in the cell — Check that you assigned the result back to r.Value and that the loop actually covers your range.
  • Macro not listed — The code may be in a sheet module rather than a standard module, or macros may be disabled. Check File > Options > Trust Center > Macro Settings, and enable macros for trusted workbooks only.
  • Wrong characters replaced — Confirm case sensitivity and that the search string has no hidden spaces. Use Len and Asc to inspect characters.
  • Runtime error 13 (Type mismatch) — The cell may contain an error value. Guard with If Not IsError(r.Value) Then.
  • Code lost after saving — The file was saved as .xlsx. Re-save as .xlsm and re-add the module.

Frequently Asked Questions

Does VBA Replace change the original string?

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

How do I replace only the first occurrence?

Set the Count argument to 1: Replace(s, "a", "b", 1, 1).

Can I replace multiple different characters at once?

Not in one call. Nest Replace calls or loop through a list of characters.

Is Replace case-sensitive by default?

Yes, it uses binary comparison. Pass vbTextCompare as the sixth argument to ignore case.

Can I use wildcards like * in Replace?

No. Wildcards are treated as literal characters. Use Like or a RegExp object for pattern matching.

Why does my macro overwrite formulas?

Writing to .Value replaces whatever is in the cell, including formulas. Write results to a different column or convert formulas to values first.