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.

Beginner 16 min read

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

FunctionReturnsExampleResult
Len(text)Number of charactersLen("INV-1042")8
Left(text, n)First n charactersLeft("INV-1042", 3)INV
Right(text, n)Last n charactersRight("INV-1042", 4)1042
Mid(text, start, n)n characters from position startMid("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.

VBA
Option Explicit

Sub InStrDemo()
    Dim email As String
    Dim atPos As Long

    email = "[email protected]"
    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 Sub
InStr basics

Note 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:

VBA
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 Sub
Get the file name and extension from a path

On 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. LTrim and RTrim trim one side only.
  • UCase and LCase convert to upper or lower case. For "Proper Case" use StrConv(text, vbProperCase).
  • Replace(text, find, replaceWith) swaps every occurrence. Use it to remove characters by replacing them with "".
VBA
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
Clean a column of imported customer names
A
1Customer
2··harbor foods
3BAKER LTD··
4cole & co
5evans··plc

Before CleanNames (dots show stray spaces)

A
1Customer
2Harbor Foods
3Baker Ltd
4Cole & Co
5Evans 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.

VBA
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
Split full names into first and last name
ABC
1Full nameFirstLast
2Anna BergAnnaBerg
3Luis Miguel OrtegaLuisOrtega
4Priya ShahPriyaShah
5Tom EvansTomEvans

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:

VBA
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 Sub
Turn "Last, First" into "First Last"

Formatting 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:

ExpressionResult
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:

  • vbCrLf is a line break for message boxes and text files (vbNewLine is equivalent). Inside a cell use vbLf (or Chr(10)), and turn on Wrap Text to see it.
  • vbTab is 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 &:

VBA
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 Sub
Build a file name and a summary message

The 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 Trim to remove inner spaces: it only trims the ends.
  • Wrong InStr argument order: InStr("@", email) searches for the email inside "@" and returns 0.
  • Forgetting that InStr returns 0, not an error: test > 0, not for an error.
  • Off-by-one errors: Left(email, atPos) includes the @; you need atPos - 1.
  • Case-sensitive comparisons that fail on "north" versus "North".
  • Using + to join text (see Operators and expressions in VBA).
  • Indexing Split from 1: the first piece is parts(0).

Check yourself

1. What does InStr("INV-1042", "X") return?

2. What does VBA's Trim(" New York ") return?

3. After parts = Split("Anna Maria Berg", " "), what is parts(UBound(parts))?

4. Which expression gives "INV" from "INV-1042"?

5. What should you use for a line break inside a cell value?