Excel VBA String Loop: Step-by-Step Guide
In this article
A VBA string loop is simply a loop that walks through characters in a text string one at a time, so you can inspect, transform, or rebuild that text. The shortest working pattern uses For i = 1 To Len(myString) and Mid(myString, i, 1) inside the loop; that gives you each character in order. You do not need any add-in, just the Visual Basic Editor that ships with Excel.
What You'll Need
- Excel for Windows or Mac with macros enabled (the Developer tab visible, or press Alt+F11 / Option+F11 to open the editor).
- A workbook saved as
.xlsmif you want to keep the macro. Plain.xlsxfiles discard VBA code when saved. - Macro security set to allow macros in trusted locations, or you will see a security warning each time you open the file.
- A cell or variable containing the text you want to process. For practice, put a sentence in A1.
Step-by-Step
- Open the editor. Press Alt+F11 (Windows) or Option+F11 (Mac) to open the Visual Basic Editor. Menu labels can differ slightly by Excel version and region, but the editor itself is the same tool.
- Insert a module. In the editor, choose Insert > Module. A blank code window appears. All the code below goes there.
- Write the skeleton. Start with a Sub and declare your variables. Use
Dim i As Longfor the counter andDim s As Stringfor the text. Long is safer than Integer because strings can be very long. - Read the text into a variable. For example,
s = Range("A1").Value. If the cell is empty,swill be an empty string and the loop will simply not run, which is fine. - Add the loop. Type
For i = 1 To Len(s)on one line andNext ion a later line. Everything between them runs once per character. - Extract each character. Inside the loop, use
Mid(s, i, 1). That returns one character starting at positioni. Store it in a variable if you need to test it, for examplech = Mid(s, i, 1). - Do something with each character. A common pattern is to build a new string:
result = result & UCase(ch). Becauseresultstarts as an empty string, each pass appends one character, and after the loop you have the full transformed text. - Write the result back. After
Next i, useRange("B1").Value = result. Run the macro with F5 and check B1. - Test edge cases. Try an empty cell, a single character, and text with spaces. The loop should handle all three without error. If you need to skip spaces, add
If ch <> " " Thenaround the append step. - Save as macro-enabled. Use File > Save As and pick Excel Macro-Enabled Workbook (.xlsm). Saving as .xlsx will prompt you to lose the macro.
A complete minimal example looks like this: Sub LoopString(), then Dim i As Long, s As String, result As String, then s = Range("A1").Value, then For i = 1 To Len(s), then result = result & UCase(Mid(s, i, 1)), then Next i, then Range("B1").Value = result, then End Sub. That is the whole idea; everything else is variations on what you do inside the loop.
Common Mistakes
- Starting at zero. VBA strings are 1-based, so
Mid(s, 0, 1)is invalid. Always start at 1. - Using the wrong length.
Len(s)returns the current length. If you modifysinside the loop, the endpoint can change; work on a separate variable instead. - Forgetting to initialise the result. If
resultis not empty at the start, you will get leftover text appended. Setresult = ""before the loop. - Comparing characters with
=and case. VBA's default comparison is case-insensitive in many contexts, soch = "a"may match "A". UseStrComp(ch, "a", vbBinaryCompare)when case matters. - Looping over a huge string one character at a time. It works, but for very long text a different approach such as
ReplaceorSplitis faster. Character loops are best for logic that truly needs each character. - Saving as .xlsx. The code disappears. Use .xlsm.
Tips
- Use
Mid$instead ofMidwhen you know the result is a string; the dollar-sign versions are slightly faster. - Use
AscandChrto inspect or build characters by code, which helps with non-printing characters like tabs. - Turn on
Option Explicitat the top of the module so undeclared variables are flagged. It catches most typos early. - Step through with F8 rather than F5 when debugging; hover over variables to see their current values.
- If you only need to replace or remove characters,
Replace(s, "a", "b")is simpler and faster than a loop.
Troubleshooting
If nothing happens when you press F5, check that the cursor is inside the Sub and that the macro name is not duplicated elsewhere. If you get a "Sub or Function not defined" error, look for a misspelled function name such as Lenn or Midd. If the result cell is blank, confirm the input cell actually contains text and that you assigned the result back to a cell. If you see a security warning, enable macros for that file or move it to a trusted location. If the macro runs but produces the wrong text, add a Debug.Print ch inside the loop and watch the Immediate Window (Ctrl+G) to see each character as it is processed. If Excel becomes slow or unresponsive, you may be looping over an enormous range; stop the macro with Esc and narrow the input.
Frequently Asked Questions
How do I loop through each character in a string in VBA?
Use For i = 1 To Len(s) and read Mid(s, i, 1) inside the loop. That is the standard pattern.
Can I loop through words instead of characters?
Yes. Use Split(s, " ") to get an array of words, then loop with For i = LBound(words) To UBound(words). This is usually faster than scanning character by character.
Why does my loop skip the first character?
You probably started at 0 or used Mid(s, i + 1, 1) by mistake. VBA string positions begin at 1, so start the counter at 1.
How do I handle uppercase and lowercase separately?
Use StrComp with vbBinaryCompare for case-sensitive comparison, or convert with UCase / LCase before testing.
Is a character loop slow?
For short text it is fine. For very long strings, built-in functions like Replace, Split, or InStr are faster because they run in compiled code rather than one VBA pass per character.
Can I stop the loop early?
Yes. Use Exit For inside the loop when a condition is met, for example when you find the first digit in the string.