Smart Systems for Home

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

Excel VBA: Replace Text in a 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 text inside a string in Excel VBA, use the built-in Replace function: Replace(expression, find, replace, [start], [count], [compare]). For example, Replace("Hello World", "World", "Excel") returns "Hello Excel". This works on any text variable, cell value, or literal string, and it does not alter the original string unless you assign the result back to a variable or cell. You can run it from the Visual Basic Editor (VBE) or inside a macro that loops through a range.

What You'll Need

  • Excel installed on Windows or Mac. The VBA editor is available in all desktop versions; the steps below are written for the Windows VBE, but the code is identical on Mac.
  • Macros enabled. If macros are disabled, you can still open the VBE, but running a macro may be blocked. Check File > Options > Trust Center > Trust Center Settings > Macro Settings (labels can differ slightly by version and region).
  • Basic familiarity with opening the VBE: press Alt+F11 on Windows, or Option+F11 on Mac.
  • A workbook where you can insert a module. No add-ins are required.

Step-by-Step

  1. Open the Visual Basic Editor. In Excel, press Alt+F11 (Windows) or Option+F11 (Mac). If the Project Explorer is not visible, press Ctrl+R (Windows) or use View > Project Explorer.
  2. Insert a standard module. In the Project Explorer, right-click your workbook name, choose Insert > Module. A blank code window opens. This is where your macro will live.
  3. Write a simple Replace example. Type the following into the module:
    Sub SimpleReplace()
        Dim original As String
        Dim result As String
        original = "Order #1234 shipped"
        result = Replace(original, "#1234", "#5678")
        MsgBox result
    End Sub
    This replaces the order number and shows the new string in a message box.
  4. Run the macro. Place the cursor inside the subroutine and press F5, or use Run > Run Sub/UserForm. A message box should display Order #5678 shipped.
  5. Replace text in a worksheet cell. To change the actual cell value, assign the result back to the cell. For example:
    Sub ReplaceInCell()
        Dim txt As String
        txt = Range("A1").Value
        Range("A1").Value = Replace(txt, "old", "new")
    End Sub
    Change the range and the search/replace words to match your data.
  6. Loop through a range. To apply the replacement to many cells, use a For Each loop:
    Sub ReplaceInRange()
        Dim c As Range
        For Each c In Range("A1:A10")
            If Not IsEmpty(c.Value) Then
                c.Value = Replace(c.Value, "-old-", "-new-")
            End If
        Next c
    End Sub
    This checks for empty cells to avoid errors.
  7. Control case sensitivity. By default, Replace is case-sensitive (binary comparison). To ignore case, add vbTextCompare as the last argument:
    result = Replace(original, "excel", "VBA", 1, -1, vbTextCompare)
    The 1 is the start position, and -1 means replace all occurrences.
  8. Limit the number of replacements. The count argument sets how many matches to replace. For example, Replace("a a a", "a", "b", 1, 2) returns "b b a". Use -1 or omit it to replace every occurrence.
  9. Test with a message box before writing to cells. Always preview the result with MsgBox or Debug.Print (view output in the Immediate Window with Ctrl+G). This prevents accidental data changes.
  10. Save your workbook as macro-enabled. Use File > Save As and choose Excel Macro-Enabled Workbook (*.xlsm). Otherwise your macro will be lost when you close the file.

Common Mistakes

  • Forgetting to assign the result. Replace(original, "a", "b") alone does nothing. You must write original = Replace(original, "a", "b") or assign to a new variable.
  • Assuming case-insensitivity. Without vbTextCompare, "Excel" and "excel" are treated differently.
  • Using Replace on a Range object directly. Range("A1").Replace is a different method with its own arguments (What, Replacement, LookAt, SearchOrder, MatchCase). It works, but it is not the same as the VBA Replace function. Mixing them up causes type mismatches.
  • Replacing in empty cells. If a cell is empty, c.Value is Empty, and passing it to Replace can cause unexpected results. Guard with If Not IsEmpty(c.Value).
  • Leaving the count argument as 0. A count of 0 replaces nothing. Use -1 or omit it for all occurrences.
  • Not saving as .xlsm. Standard .xlsx files strip macros on save.

Tips

  • Use vbNullString to delete text: Replace(txt, "remove", "") removes all instances of "remove".
  • For multiple replacements, chain them: txt = Replace(Replace(txt, "a", "b"), "c", "d"). Each call works on the result of the previous one.
  • Use Debug.Print instead of MsgBox when testing loops; it prints to the Immediate Window and does not interrupt execution.
  • If you need to replace using wildcards or patterns, the VBA Replace function does not support them. Use the Range.Replace method with LookAt:=xlPart or a regular expression via RegExp object (requires setting a reference to Microsoft VBScript Regular Expressions).
  • Always back up your workbook before running a macro that writes to many cells.
  • Remember that Replace returns a new string; it never modifies the original in place.

Troubleshooting

  • "Compile error: Expected: =" — You likely wrote Replace(...) as a statement without assigning it. Assign the result to a variable or cell.
  • Nothing happens when you run the macro — Check that the macro is in a standard module and that you pressed F5 while the cursor is inside the correct subroutine. Also confirm macros are enabled.
  • "Type mismatch" — You may be passing a Range object instead of its .Value. Use c.Value or Range("A1").Value.
  • Replacement not working on some cells — The search text may include leading/trailing spaces or hidden characters. Use Trim or inspect with Debug.Print Len(c.Value).
  • Macro lost after saving — Save as .xlsm. If you already saved as .xlsx, the macro is gone; you must re-enter it.
  • Case-sensitive surprises — Add vbTextCompare as the sixth argument.

Frequently Asked Questions

Can I replace text in a string without VBA?

Yes. Excel's Find & Replace (Ctrl+H) works on cell contents, and the SUBSTITUTE function works in formulas. VBA is needed only when you want to automate the process or work with strings in code.

Does VBA Replace modify the original string?

No. The Replace function returns a new string. You must assign the result back to a variable or cell to keep the change.

How do I replace only the first occurrence?

Set the count argument to 1: Replace(txt, "find", "replace", 1, 1).

Can I use wildcards with VBA Replace?

No. The VBA Replace function does not support wildcards. Use the Range.Replace method with LookAt:=xlPart for simple wildcard-like behavior, or a regular expression for complex patterns.

Why does my replacement ignore case?

It does not by default; VBA Replace is case-sensitive. If you want case-insensitive replacement, add vbTextCompare as the last argument.

What is the difference between Replace and Substitute?

Substitute is a worksheet function used in formulas. Replace is a VBA function used in macros. They behave similarly but live in different environments.