VBA course · Lesson 12 of 33
Working with text (strings) in VBA
Cut, search, clean and build text in VBA with Len, Left, Mid, InStr, Replace, Trim, Split, Join, Format, StrComp, vbCrLf and Chr, using real data examples.
A large part of everyday Excel automation is about text: splitting full names into first and last names, pulling a code out of a longer description, cleaning extra spaces from an export, building file names such as Invoice_INV-1042_HarborFoods.pdf, or writing a friendly message. In VBA a piece of text is called a string, and the language comes with a rich set of string functions. Many of them have the same names as the worksheet functions you may know, such as LEFT, MID and TRIM, but there are some important differences, which this lesson points out.
Declare text variables As String. String literals are written in double quotes: "Harbor Foods". To put a double quote inside a string, double it: "He said ""hello""" gives He said "hello".
Length and pieces: Len, Left, Right, Mid
| Function | Returns | Example | Result |
|---|---|---|---|
| Len(text) | Number of characters | Len("INV-1042") | 8 |
| Left(text, n) | First n characters | Left("INV-1042", 3) | INV |
| Right(text, n) | Last n characters | Right("INV-1042", 4) | 1042 |
| Mid(text, start, n) | n characters from position start | Mid("INV-1042", 5, 2) | 10 |
Positions in VBA strings start at 1, as in Excel. If you leave out the length in Mid, you get everything to the end: Mid("INV-1042", 5) is 1042. Asking for more characters than exist is not an error; you simply get what is there.
Finding text: InStr and InStrRev
InStr returns the position of one string inside another, or 0 if it is not found. It is the VBA cousin of FIND and SEARCH, with one big advantage: a result of 0 instead of an error.
Option Explicit
Sub InStrDemo()
Dim email As String
Dim atPos As Long
email = "maria.lopez@harborfoods.com"
atPos = InStr(email, "@") ' 12
Debug.Print "User name: " & Left(email, atPos - 1) ' maria.lopez
Debug.Print "Domain: " & Mid(email, atPos + 1) ' harborfoods.com
' Case-insensitive search: start position 1 and vbTextCompare
Debug.Print InStr(1, "Harbor FOODS", "foods", vbTextCompare) ' 8
If InStr(email, "harbor") > 0 Then Debug.Print "Harbor Foods address"
End SubNote the argument order: InStr([start,] text, find [, compare]). The optional start comes first, and if you want to pass the compare argument you must pass the start too. InStrRev searches from the end and is perfect for the last backslash in a path or the last dot in a file name:
Option Explicit
Sub SplitPath()
Dim fullPath As String
Dim fileName As String
Dim ext As String
fullPath = "C:\Reports\2026\Sales_March.xlsx"
fileName = Mid(fullPath, InStrRev(fullPath, "\") + 1) ' Sales_March.xlsx
ext = Mid(fileName, InStrRev(fileName, ".") + 1) ' xlsx
MsgBox "File: " & fileName & vbCrLf & "Type: " & ext
End SubOn a Mac, paths use / (for example /Users/maria/Reports/Sales_March.xlsx). Code that must run on both systems can use Application.PathSeparator instead of a hard-coded backslash.
Cleaning text: Trim, UCase, LCase, Replace
Trim(text)removes spaces at the start and end. Unlike the worksheet TRIM, it does not reduce double spaces in the middle.LTrimandRTrimtrim one side only.UCaseandLCaseconvert to upper or lower case. For "Proper Case" useStrConv(text, vbProperCase).Replace(text, find, replaceWith)swaps every occurrence. Use it to remove characters by replacing them with"".
Option Explicit
Sub CleanNames()
Dim cell As Range
Dim s As String
For Each cell In Range("A2:A6")
s = cell.Value
s = Replace(s, Chr(160), " ") ' non-breaking spaces from web pages
s = Trim(s) ' outer spaces
Do While InStr(s, " ") > 0 ' inner double spaces
s = Replace(s, " ", " ")
Loop
cell.Value = StrConv(s, vbProperCase)
Next cell
End Sub| A | |
|---|---|
| 1 | Customer |
| 2 | ··harbor foods |
| 3 | BAKER LTD·· |
| 4 | cole & co |
| 5 | evans··plc |
Before CleanNames (dots show stray spaces)
| A | |
|---|---|
| 1 | Customer |
| 2 | Harbor Foods |
| 3 | Baker Ltd |
| 4 | Cole & Co |
| 5 | Evans Plc |
After CleanNames
The Do While loop is needed because one Replace of two spaces by one only halves long runs of spaces. Alternatively, call the worksheet version: Application.WorksheetFunction.Trim(s) does the inner clean-up in one step (see Using Excel worksheet functions in VBA). Chr(160) is the non-breaking space that often arrives with data copied from websites; Trim does not remove it, which is a classic reason why two "identical" names do not match.
Comparing text: StrComp
StrComp(a, b, vbTextCompare) returns 0 when the strings are equal ignoring case, -1 when a sorts before b, and 1 when after. It is a tidy way to compare without changing case: If StrComp(region, "north", vbTextCompare) = 0 Then. Use vbBinaryCompare for an exact, case-sensitive comparison.
Splitting and joining: Split and Join
Split cuts a string at a delimiter and returns an array of pieces, numbered from 0. Join does the opposite. Arrays are covered fully in Arrays in VBA: static, dynamic and fast range processing, but these two functions are simple enough to use right away.
Option Explicit
Sub SplitNames()
Dim r As Long
Dim parts() As String
For r = 2 To 5
parts = Split(Trim(Cells(r, "A").Value), " ")
Cells(r, "B").Value = parts(0) ' first word
Cells(r, "C").Value = parts(UBound(parts)) ' last word
Next r
End Sub| A | B | C | |
|---|---|---|---|
| 1 | Full name | First | Last |
| 2 | Anna Berg | Anna | Berg |
| 3 | Luis Miguel Ortega | Luis | Ortega |
| 4 | Priya Shah | Priya | Shah |
| 5 | Tom Evans | Tom | Evans |
After SplitNames: UBound finds the last word even when there is a middle name
UBound(parts) gives the highest index, so parts(UBound(parts)) is always the last piece. If the cell is empty, Split returns an empty array and parts(0) fails, so check Len(Trim(...)) > 0 first in real code.
Join(array, ", ") glues the pieces back with any separator. Together they make light work of re-ordering text:
Option Explicit
Function FirstLast(ByVal lastFirst As String) As String
Dim parts() As String
parts = Split(lastFirst, ",")
If UBound(parts) = 1 Then
FirstLast = Trim(parts(1)) & " " & Trim(parts(0))
Else
FirstLast = Trim(lastFirst)
End If
End Function
Sub TestFirstLast()
Debug.Print FirstLast("Kowalski, Jan") ' Jan Kowalski
Debug.Print Join(Split("A-B-C", "-"), "/") ' A/B/C
End SubFormatting numbers and dates as text: Format
Format(value, pattern) turns a number or date into text in the shape you want, much like Excel's TEXT function:
| Expression | Result |
|---|---|
| Format(1249.5, "#,##0.00") | 1,249.50 |
| Format(0.075, "0.0%") | 7.5% |
| Format(42, "00000") | 00042 |
| Format(#3/15/2026#, "yyyy-mm-dd") | 2026-03-15 |
| Format(#3/15/2026#, "dd mmm yyyy") | 15 Mar 2026 |
The thousands and decimal separators follow the regional settings of the computer, so a German PC shows 1.249,50. Use the result for display or file names; keep the original number for calculations.
Line breaks and special characters
Special characters are produced with built-in constants or Chr:
vbCrLfis a line break for message boxes and text files (vbNewLineis equivalent). Inside a cell usevbLf(orChr(10)), and turn on Wrap Text to see it.vbTabis a tab character.Chr(34)is a double quote, handy when building formulas as text.Asc("A")returns 65, the character code;Chr(65)turns it back into "A".
Building longer strings
Messages, e-mail bodies and file names are built piece by piece with &:
Option Explicit
Sub BuildInvoiceText()
Dim invNo As String
Dim customer As String
Dim amount As Double
Dim fileName As String
Dim msg As String
invNo = "INV-1042"
customer = "Harbor Foods"
amount = 1249.5
fileName = "Invoice_" & invNo & "_" & Replace(customer, " ", "") & ".pdf"
msg = "Invoice " & invNo & " is ready." & vbCrLf & vbCrLf
msg = msg & "Customer: " & customer & vbCrLf
msg = msg & "Amount: " & Format(amount, "#,##0.00") & vbCrLf
msg = msg & "File: " & fileName
MsgBox msg, vbInformation, "Invoice created"
End SubThe msg = msg & ... pattern is clear and fine for a few dozen pieces. If you join tens of thousands of pieces in a loop, collect them in an array and call Join once; that is much faster.
Mid as a statement
Mid can also appear on the left of an assignment to overwrite characters in place: Mid(code, 1, 3) = "INV" replaces the first three characters of code. It cannot change the length of the string. It is rarely needed but good to recognise.
Common mistakes
- Expecting VBA
Trimto remove inner spaces: it only trims the ends. - Wrong
InStrargument order:InStr("@", email)searches for the email inside "@" and returns 0. - Forgetting that
InStrreturns 0, not an error: test> 0, not for an error. - Off-by-one errors:
Left(email, atPos)includes the @; you needatPos - 1. - Case-sensitive comparisons that fail on "north" versus "North".
- Using
+to join text (see Operators and expressions in VBA). - Indexing
Splitfrom 1: the first piece isparts(0).
Check yourself
1. What does InStr("INV-1042", "X") return?
InStr returns 0 when the text is not found, so test with > 0.
2. What does VBA's Trim(" New York ") return?
VBA Trim only removes leading and trailing spaces. WorksheetFunction.Trim also reduces inner runs of spaces.
3. After parts = Split("Anna Maria Berg", " "), what is parts(UBound(parts))?
UBound returns the highest index (2), which holds the last word.
4. Which expression gives "INV" from "INV-1042"?
Left takes characters from the start; positions in Mid start at 1, not 0.
5. What should you use for a line break inside a cell value?
Cells use a line feed; vbCrLf is meant for message boxes and text files.