String functions in VBA

Lists rarely arrive the way you need them: names as "Last, First" in one cell, item numbers with stray spaces and mixed case, email addresses you have to build yourself. A handful of string functions lets a macro fix that for every row.

In short: Left(text, 2) returns the first two characters, Mid(text, 4) everything from the fourth, InStr(text, ",") the position of the comma, Replace(text, " ", "") swaps characters, Trim removes spaces at the edges, and UCase and LCase change the case. & joins text together.

What you need to know: For Next and joining text with & from Operators.

Try it right now

Task The item numbers from the import have spaces at the edges and mixed upper and lower case. Write a macro CleanUp that writes each number from column A (row 2 down to the last) into column B without leading or trailing spaces and in capitals.

ABCD
1ImportItem number
2 bp-1040
3TN-2210
4 or-0815
5Hn-3300
6ks-0400

The string functions you need most

FunctionWhat it doesExampleResult
Len(text)number of charactersLen("BP-1040")7
Left(text, n)the first n charactersLeft("BP-1040", 2)BP
Right(text, n)the last n charactersRight("BP-1040", 4)1040
Mid(text, start, n)n characters from position start; without n, to the endMid("BP-1040", 4, 2)10
InStr(text, find)position of the first match, 0 if not foundInStr("Carter, Emily", ",")7
Replace(text, old, new)replaces every occurrenceReplace("Mary Ann", " ", "")MaryAnn
Trim(text)removes spaces at the start and endTrim(" bp-1040 ")bp-1040
UCase, LCaseall capitals or all lower caseUCase("bp-1040")BP-1040
Split(text, delimiter)cuts text into an array, counting from 0Split("BP-1040-07", "-")(2)07

You can nest the functions, and VBA works from the inside out: UCase(Trim(text)) removes the spaces first, then capitalises. Positions start at 1: the first character is at position 1.

Split text at a delimiter

The pattern you will use most: InStr finds the delimiter, Left takes everything before it, Mid everything after it. Because the position is found again for every row, it works for names of any length.

fullName = "Carter, Emily"
commaPos = InStr(fullName, ",")                ' 7
lastName = Left(fullName, commaPos - 1)        ' Carter
firstName = Trim(Mid(fullName, commaPos + 1))  ' Emily

The - 1 leaves out the comma itself, the + 1 starts just after it, and Trim removes the space that follows the comma.

Task Column A has names in the form "Last, First". Write a macro SplitNames that writes the first name to column B and the last name to column C for every row from 2, without spaces at the edges. Use InStr to find the comma.

ABCD
1NameFirst nameLast name
2Carter, Emily
3Hughes, Daniel
4Okafor, Grace
5Lloyd-Jones, Megan
6Ramirez, Luis

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Join and replace text

Use & to chain text and cell contents, and Replace to swap characters. Replace changes every occurrence, not only the first. Email addresses and file names often need both:

address = LCase(firstName & "." & lastName)  ' sean.o'brien
address = Replace(address, "'", "")           ' sean.obrien
address = address & "@example.com"

Watch out: Replace and InStr are case-sensitive by default. InStr("North", "n") returns 0, because the N at the start is a capital. When case should not matter, compare lower case with lower case: InStr(LCase(text), "n").

Task Email addresses are needed for new staff: firstname.lastname@example.com, all lower case, with spaces and apostrophes removed. Write a macro BuildEmails that writes the address to column C for every row from 2.

ABCD
1First nameLast nameEmail
2EmilyCarter
3SeanO'Brien
4Mary AnnLloyd
5DanielVan Dyke
6GraceOkafor

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Common mistakes

Delimiter not found

If InStr cannot find the character, it returns 0. Left(text, 0 - 1) is then a negative length, and VBA reports "Run-time error '5': Invalid procedure call or argument". It happens when you search for the wrong character (a semicolon instead of a comma) or when one row is laid out differently. If in doubt, check first with If commaPos > 0 Then.

One character too many

Left(fullName, commaPos) without - 1 keeps the comma, and Mid(fullName, commaPos + 1) without Trim keeps the space. The exercise points to the first cell that differs; a leading space is hard to see in a cell.

Fixed positions

Left(text, 6) fits "Carter" but not "Lloyd-Jones". Check tests with other names. Let InStr find the position instead of counting it yourself.

+ instead of &

+ also joins two pieces of text, but as soon as one side is a number VBA tries to add. "R-" + 5 gives "Run-time error '13': Type mismatch". For text, always use &.

VBA Trim is not the TRIM function

VBA's Trim only removes spaces at the edges. Double spaces in the middle stay, unlike Excel's TRIM function. For that behaviour there is WorksheetFunction.Trim.

In real Excel

For a one-off split, Data > Text to Columns or Flash Fill is often enough. A macro pays off when the same clean-up comes round with every import, or when you need rules the wizards do not know. Try string functions in the Immediate window (Ctrl+G in the VBA editor): type ? Mid("BP-1040", 4) and press Enter to see the result straight away.

FAQ

How do I find the last occurrence of a character?

With InStrRev. It searches from the end but still returns the position counted from the start. Handy for file extensions or the part after the last hyphen.

How do I check whether text contains something?

With If InStr(text, "Ltd") > 0 Then. If case should not matter, compare both sides in lower case.

When should I use Split instead of InStr?

When the text has several parts with the same delimiter, such as "BP-1040-07". Split returns all parts at once in an array. Working with arrays is covered in Arrays.

How do I get a number out of text?

With Val("1040") or CLng. Val reads from the left for as long as it finds digits, and always expects a period as the decimal point.

Learn this next: dates in VBA

Work out due dates, count days and spot weekends with DateAdd, DateDiff, Weekday and Format.

Learn dates in VBA

Write to us

Choose language

Select your preferred language