Excel VBA: Replace Character in String (Step-by-Step)
In this article
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
- 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.
- Insert a module. In the editor, choose Insert > Module. Code placed in a standard module is available to every sheet in the workbook.
- Write the simplest replacement. Type a short test procedure:
This replaces every hyphen with a forward slash and showsSub SimpleReplace() Dim s As String s = "A-B-C" s = Replace(s, "-", "/") MsgBox s End SubA/B/C. - 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. - Replace only the first occurrence. Add the optional
Countargument:Replace(s, "-", "/", 1, 1). The fourth argument isStart(where to begin, 1-based) and the fifth isCount(how many replacements; -1 means all). - Control case sensitivity. The sixth argument is
Compare. UsevbBinaryComparefor case-sensitive matching orvbTextComparefor case-insensitive. Example:Replace("Apple", "a", "x", 1, -1, vbTextCompare)returnsxpple. - Apply it to a cell. Read the value, replace, then write it back:
This turns spaces into underscores in A1:A10. Adjust the range to your data.Sub ReplaceInCell() Dim r As Range For Each r In Range("A1:A10") r.Value = Replace(r.Value, " ", "_") Next r End Sub - Handle empty cells. Before replacing, guard with
If Len(r.Value) > 0 Thenso blank cells are skipped and stay blank. - 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.
- 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 changesunless 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
vbTextComparewhen 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.
Replacetreats*and?as literal characters, not wildcards. If you need pattern matching, useLikeor a RegExp object instead. - Running on the wrong sheet. Unqualified
Range("A1")refers to the active sheet. Qualify withWorksheets("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
Trimafter 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.Printin 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.Valueand 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
LenandAscto 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.