Smart Systems for Home

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

Word VBA String Functions: A How-To Guide

· 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

Word VBA string functions let you inspect, slice, search, and rebuild text inside a macro — for example, pulling a client name out of a paragraph, cleaning up double spaces, or converting a selection to title case. You do this in the Visual Basic Editor (VBE) that ships with Word; no add-ins are required. The core functions are Len, Left, Right, Mid, InStr, InStrRev, Replace, Trim, LTrim, RTrim, UCase, LCase, StrComp, and Split/Join. This guide shows how to open the editor, run a working macro, and use each function correctly on Word text.

What You'll Need

  • Microsoft Word for Windows or Mac (the VBE is included; on Mac it is under Tools > Macro > Visual Basic Editor).
  • A document you can safely test on — use a copy, because macros can overwrite text.
  • Macro security set to allow macros. In Word, go to File > Options > Trust Center > Trust Center Settings > Macro Settings and choose “Disable all macros with notification” so you can enable your own macro when prompted. On Mac, use Word > Preferences > Security & Privacy.
  • Basic familiarity with variables and MsgBox. No prior VBA experience is assumed.

Menu labels can differ slightly by Word version, platform, and region; if a path looks different, look for the closest matching item.

Step-by-Step

  1. Open the Visual Basic Editor. In Word, press Alt+F11 (Windows) or use Tools > Macro > Visual Basic Editor (Mac). The editor opens in its own window.
  2. Insert a module. In the VBE, choose Insert > Module. A blank code window appears. All your string-function code goes here.
  3. Write a minimal test macro. Type this exactly:
    Sub TestStrings()
        Dim s As String
        s = "  Hello, World  "
        MsgBox Len(s)              ' 16
        MsgBox "[" & Trim(s) & "]" ' [Hello, World]
        MsgBox Left(Trim(s), 5)    ' Hello
        MsgBox Right(Trim(s), 5)   ' World
        MsgBox Mid(Trim(s), 8, 5)  ' World
    End Sub
    Run it with F5. Each message box shows one result; click OK to advance. This proves the editor and macro security are working before you touch real document text.
  4. Read text from the document. Replace the fixed string with document content. For the current selection:
    Dim s As String
    s = Selection.Text
    For a whole paragraph, use ActiveDocument.Paragraphs(1).Range.Text. Word paragraph text usually ends with a paragraph mark (Chr(13)), so trim it first: s = Trim(ActiveDocument.Paragraphs(1).Range.Text).
  5. Find a substring with InStr. InStr(1, s, "World", vbTextCompare) returns the position of “World” (case-insensitive because of vbTextCompare). If the text is not found, it returns 0 — always test for that before using Mid, or you will slice at position 0 and get an error or wrong result.
  6. Search from the end with InStrRev. InStrRev(s, "o") returns the position of the last “o”. This is useful for finding a file extension or the last word in a sentence.
  7. Extract with Left, Right, and Mid. Left(s, n) takes the first n characters; Right(s, n) takes the last n; Mid(s, start, length) takes a slice. If length is omitted, Mid returns everything from start to the end. Positions are 1-based, not 0-based, which is the most common source of off-by-one errors.
  8. Replace text with Replace. Replace(s, "World", "VBA") returns a new string; it does not change s unless you assign it back: s = Replace(s, "World", "VBA"). Add vbTextCompare as the sixth argument for case-insensitive replacement.
  9. Clean whitespace. Trim removes leading and trailing spaces; LTrim and RTrim remove only one side. To collapse double spaces inside a string, loop: Do While InStr(s, " ") > 0: s = Replace(s, " ", " "): Loop.
  10. Change case. UCase(s) and LCase(s) convert the whole string. For title case, use Word's own Selection.Range.Case = wdTitleWord rather than rebuilding it character by character.
  11. Split and join. Split(s, ",") returns a zero-based array of parts; loop with For i = LBound(arr) To UBound(arr). Join(arr, "; ") rebuilds a string. This is the clean way to process comma-separated lists in a paragraph.
  12. Write the result back. Assign to a range: Selection.Range.Text = s or ActiveDocument.Paragraphs(1).Range.Text = s. Test on a copy first — this overwrites the original text.
  13. Save and reuse. Save the document as a macro-enabled file (.docm) or store the module in Normal.dotm so the macro is available in every document. Use File > Save As and choose the macro-enabled format.

Common Mistakes

  • Forgetting that positions start at 1. Mid(s, 0, 5) is invalid; the first character is position 1.
  • Ignoring a zero from InStr. If InStr returns 0, passing it to Mid causes a run-time error. Check the result first.
  • Assuming Replace changes the original. It returns a new string; you must assign it back.
  • Leaving the paragraph mark in. Range.Text often includes Chr(13); trim before comparing or splitting.
  • Case sensitivity surprises. Without vbTextCompare, InStr and Replace are case-sensitive.
  • Using a fixed-length string. Declaring Dim s As String * 20 pads or truncates; use plain Dim s As String.

Tips

  • Use Debug.Print instead of MsgBox while developing; output appears in the Immediate Window (Ctrl+G).
  • Wrap risky code in On Error GoTo handler and show the error number and description so failures are diagnosable.
  • Use vbCrLf when building multi-line strings, and vbTab for tab-separated output.
  • For Unicode or special characters, remember VBA strings are Unicode; Len counts characters, not bytes.
  • Keep a small test document with known strings so you can verify each function's output after changes.

Troubleshooting

  • Macro will not run: check Trust Center macro settings and enable macros for the document. On Mac, confirm the document is not in a read-only location.
  • “Sub or Function not defined”: the module may not be inserted, or the macro name is misspelled. Confirm the code is in a standard module, not a document module.
  • Run-time error 5 (Invalid procedure call): usually a negative or zero length passed to Left, Right, or Mid. Guard lengths with If n > 0 Then.
  • Text looks unchanged: you probably modified a copy of the string without assigning it back to the range.
  • Unexpected characters: paragraph marks, non-breaking spaces (Chr(160)), and smart quotes are not removed by Trim. Replace them explicitly.
  • Editor will not open: close and reopen Word, then try Alt+F11 again; on Mac, ensure the Visual Basic Editor is installed with your Office build.

Frequently Asked Questions

Do string functions change the document automatically?

No. They return values. You must assign the result back to a range or selection to change the document.

Are VBA string positions 0-based or 1-based?

1-based. The first character is position 1, and InStr returns 0 when no match is found.

How do I make comparisons case-insensitive?

Pass vbTextCompare to InStr or Replace, or use StrComp(a, b, vbTextCompare).

Can I use these functions on tables and headers?

Yes, if you address the right range — for example ActiveDocument.Tables(1).Cell(1,1).Range.Text or a header's Range.Text. Trim the cell end-of-cell marker first.

Why does my extracted text include a paragraph mark?

Word paragraph ranges include Chr(13). Use Trim or Replace(s, Chr(13), "") before processing.

Do these functions work in Word for Mac?

Yes, the core VBA string functions behave the same; only the menu paths to the editor differ.