Excel VBA: Replace Part of a String (Step-by-Step)
In this article
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
- 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.
- 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.
- Write a simple test procedure. Paste this in and press F5 to run it:
The message box showsSub SimpleReplace() Dim original As String Dim result As String original = "Order AB-1234 shipped" result = Replace(original, "AB", "XY") MsgBox result End SubOrder XY-1234 shipped. Note thatoriginalis unchanged; onlyresultholds the new text. - Understand the full syntax. The signature is
Replace(expression, find, replace, [start], [count], [compare]).startis the character position to begin at (default 1).countis how many replacements to make;-1or omitted means all.compareisvbBinaryCompare(default, case-sensitive) orvbTextCompare(case-insensitive). - 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". - Replace only the first occurrence. Set
countto 1:Replace(original, "-", "_", 1, 1). This is useful when a delimiter appears several times but you only want the first one changed. - Replace text inside a cell. Use the cell's
.Valueon both sides of the assignment:
Reading and writing the same cell in one statement is safe; the value is read first, then written back.Sub ReplaceInCell() With ThisWorkbook.Worksheets("Sheet1").Range("A1") .Value = Replace(.Value, "Old", "New", 1, -1, vbTextCompare) End With End Sub - 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 - Guard against errors and blanks. The
IsErrorcheck skips cells showing #N/A or similar.CStrconverts numbers and dates to text soReplacedoes not fail; without it, a numeric cell raises a type mismatch. - Speed it up for large ranges. Turn off screen updating and calculation while the loop runs, then turn them back on:
Application.ScreenUpdating = Falsebefore the loop andApplication.ScreenUpdating = Trueafter. AddApplication.Calculation = xlCalculationManualand restore it toxlCalculationAutomaticafterwards. Always restore these settings, even if an error occurs, or Excel stays sluggish until restarted. - 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.
Replacereturns a new string. If you writeReplace(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
vbTextComparewhen case should not matter. - Passing a cell object instead of its value.
Replace(Range("A1"), ...)fails or misbehaves; useRange("A1").Value. - Type mismatch on numbers. Numeric or error values need
CStrand anIsErrorcheck. - Replacing in a forward loop while deleting rows. Row numbers shift and you skip data. Loop backwards or collect rows first.
- Confusing VBA
Replacewith 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
replaceargument ("") to delete the matched text entirely. - Test your pattern on a single cell with
MsgBoxbefore 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
Replaceonly matches literal text. UseRegExpfrom 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.