VBA – Loop Through a String


You can perform logic on, or return individual characters from a string in VBA by looping through the string.

Loop Through Each Character in a String

The following is an example of looping through a string using a For…Next Loop, and returning each character in a msgbox.

Sub LoopThroughString()

Dim Counter As Integer
Dim MyString As String

MyString = "AutomateExcel" 'define string

For Counter = 1 To Len(MyString)
    'do something to each character in string
    'here we'll msgbox each character
    MsgBox Mid(MyString, Counter, 1)
Next

End Sub

The Len Function counts the total number of characters in the string. So the expression

For Counter = 1 to Len(MyString

will loop through each letter in the string.

Loop Through Each Character in a String – Alternative

Read Every Character in a String
: This example reads every character in a string from left to right and returns the result in a message box. It makes use of the Mid function.

Sub LoopThroughString()

Dim LookInHere As String
Dim Counter As Integer

'Use your own text here
LookInHere = "AutomateExcel.com"

For Counter = 1 To Len(LookInHere)
    MsgBox Mid(LookInHere, Counter, 1)
Next

End Sub
AutoMacro - VBA Code Generator

Read Every Word in a String

This example reads every word in a string from left to right and returns the result in a message box. It makes use of the Split function.

Sub LoopThroughString2()

Dim LookInHere As String
Dim Counter As Integer
Dim SplitCatcher As Variant

'Use your own text here

LookInHere = "I Heart AutomateExcel.com"

SplitCatcher = Split(LookInHere, " ")

For Counter = 0 To UBound(SplitCatcher)
    MsgBox SplitCatcher(Counter)
Next

End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

alt text

[convertkit form=4869294]


<<Return to VBA Examples

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

(No installation required!)