Word VBA String Functions: A How-To Guide
In this article
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
- 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. - Insert a module. In the VBE, choose Insert > Module. A blank code window appears. All your string-function code goes here.
- Write a minimal test macro. Type this exactly:
Run it withSub 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 SubF5. 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. - Read text from the document. Replace the fixed string with document content. For the current selection:
For a whole paragraph, useDim s As String s = Selection.TextActiveDocument.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). - Find a substring with InStr.
InStr(1, s, "World", vbTextCompare)returns the position of “World” (case-insensitive because ofvbTextCompare). If the text is not found, it returns 0 — always test for that before usingMid, or you will slice at position 0 and get an error or wrong result. - 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. - 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. Iflengthis omitted,Midreturns everything fromstartto the end. Positions are 1-based, not 0-based, which is the most common source of off-by-one errors. - Replace text with Replace.
Replace(s, "World", "VBA")returns a new string; it does not changesunless you assign it back:s = Replace(s, "World", "VBA"). AddvbTextCompareas the sixth argument for case-insensitive replacement. - Clean whitespace.
Trimremoves leading and trailing spaces;LTrimandRTrimremove only one side. To collapse double spaces inside a string, loop:Do While InStr(s, " ") > 0: s = Replace(s, " ", " "): Loop. - Change case.
UCase(s)andLCase(s)convert the whole string. For title case, use Word's ownSelection.Range.Case = wdTitleWordrather than rebuilding it character by character. - Split and join.
Split(s, ",")returns a zero-based array of parts; loop withFor i = LBound(arr) To UBound(arr).Join(arr, "; ")rebuilds a string. This is the clean way to process comma-separated lists in a paragraph. - Write the result back. Assign to a range:
Selection.Range.Text = sorActiveDocument.Paragraphs(1).Range.Text = s. Test on a copy first — this overwrites the original text. - 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
InStrreturns 0, passing it toMidcauses 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.Textoften includesChr(13); trim before comparing or splitting. - Case sensitivity surprises. Without
vbTextCompare,InStrandReplaceare case-sensitive. - Using a fixed-length string. Declaring
Dim s As String * 20pads or truncates; use plainDim s As String.
Tips
- Use
Debug.Printinstead ofMsgBoxwhile developing; output appears in the Immediate Window (Ctrl+G). - Wrap risky code in
On Error GoTo handlerand show the error number and description so failures are diagnosable. - Use
vbCrLfwhen building multi-line strings, andvbTabfor tab-separated output. - For Unicode or special characters, remember VBA strings are Unicode;
Lencounts 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, orMid. Guard lengths withIf 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 byTrim. Replace them explicitly. - Editor will not open: close and reopen Word, then try
Alt+F11again; 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.