Who this lesson is for
Every Excel user who receives data from another system ends up with the same chore: a column of codes, references or descriptions that hide several pieces of information in one cell. The order number contains the country and the year, the account string contains the cost centre, the file name contains the date. You can split such values by hand, with Flash Fill, or with worksheet formulas, but when the same export arrives every week, or holds tens of thousands of rows, a short VBA macro does it faster and the same way every time. This lesson is for people who already record or write simple macros and now want to clean text with them.
The free lab above contains the macro SplitReferenceCodes. It builds a Ref Demo sheet from six sample references such as CH-2026-04871, cuts each one into country, year and running number, and flags the one that does not have the expected shape. Below we use exactly those six values to explain how Left, Mid, Right and Len count characters, what the macro writes into the sheet, and the traps that make text cutting go quietly wrong.
The core idea: every character has a position
A string in VBA is a row of characters, and the first character is at position 1. That sounds obvious, but it is the source of most off-by-one errors, because VBA arrays created with Array() or Split() start at 0. When you cut text, think of numbered boxes: Left takes boxes from the start, Right takes boxes from the end, and Mid starts at a box number you choose and takes as many as you ask for. Len counts the boxes.
In code, the three cuts from the diagram look like this. The comments show what each line prints in the Immediate window (Ctrl+G in the Visual Basic Editor):
Dim ref As Stringref = "CH-2026-04871"Debug.Print Left(ref, 2) ' CHDebug.Print Mid(ref, 4, 4) ' 2026Debug.Print Right(ref, 5) ' 04871Debug.Print Len(ref) ' 13
The worksheet has functions with the same names and the same counting: =LEFT(A2,2), =MID(A2,4,4), =RIGHT(A2,5) and =LEN(A2). Two small differences are worth knowing. In VBA the length argument of Mid is optional, so Mid(ref, 4) returns 2026-04871; the worksheet MID always needs it. And VBA offers each function in two flavours: Left returns a Variant, Left$ returns a String. With a String variable both give the same answer, but Left$ raises an error if it receives Null, which can be useful when you would rather fail loudly than carry a Null through your code.
The functions are forgiving at the edges. Asking for more characters than exist is not an error: Left("CH", 5) returns CH and Mid(ref, 12, 10) returns 71. A start position beyond the end returns an empty string. What does raise run-time error 5, "Invalid procedure call or argument", is a negative length or a start position of 0, which usually means a calculated position came out wrong. That forgiveness is convenient, but it is also why a fixed-position macro can produce nonsense without stopping: a short value simply gives a short answer.
Worked example: the six lab references
Here are the six samples the lab macro writes to Ref Demo, with their length and the three pieces. The last column shows a single worksheet formula that reproduces the macro's country column including the guard, if you want to check its work next to the data. The references are fictional, for example the kind of order numbers a Swiss company might issue per country and year.
| A: Reference | =LEN(A2) | Country Left(ref, 2) | Year Mid(ref, 4, 4) | Number Right(ref, 5) | =IF(LEN(A2)=13,LEFT(A2,2),"CHECK: "&LEN(A2)&" characters") |
|---|---|---|---|---|---|
| CH-2026-04871 | 13 | CH | 2026 | 04871 | CH |
| DE-2026-11250 | 13 | DE | 2026 | 11250 | DE |
| CH-2025-00042 | 13 | CH | 2025 | 00042 | CH |
| AT-2026-93117 | 13 | AT | 2026 | 93117 | AT |
| CH-26-4871 | 10 | not cut: "CHECK: 10 characters" | CHECK: 10 characters | ||
| FR-2026-70008 | 13 | FR | 2026 | 70008 | FR |
Without the length check, the fifth row would not fail. It would produce CH, 26-4 and -4871, three plausible-looking cells with a year that is not a year. That is the real reason for If Len(ref) = 13 in the lab: cutting at fixed positions is only correct while every value has the same shape, and the cheapest way to know that is to count the characters first.
One more detail in the output is easy to miss. Mid and Right return text, but when VBA writes a string such as "04871" or "2026" into a cell formatted as General, Excel interprets it the way it would interpret your typing. The year becomes the number 2026, which is fine, but 04871 becomes the number 4871 and 00042 becomes 42: the leading zeros are gone. If the running number is an identifier rather than a quantity, format the target column as text before writing, with ws.Range("D:D").NumberFormat = "@", and the zeros stay.
How to run the lab macro and adapt it to your data
- Save the workbook as an Excel Macro-Enabled Workbook (.xlsm) via File → Save As, or the code will not be kept.
- Press
Alt+F11to open the Visual Basic Editor, then choose Insert → Module. - Paste the complete
SplitReferenceCodeslisting from the lab, click anywhere inside it and pressF5. A sheet called Ref Demo appears with four columns. - Press
Ctrl+Gfor the Immediate window and try a few cuts yourself, for example?Mid("CH-2026-04871", 9), which prints04871. - To process your own column instead of the built-in samples, replace the
samples = Array(...)line with a read from the sheet, for examplesamples = Application.Transpose(Worksheets("Orders").Range("A2:A500").Value), Because that array starts at 1 rather than 0, also change the loop toFor r = 1 To UBound(samples), the sizing line toReDim out(1 To UBound(samples), 1 To 4), and everyout(r + 1, ...)toout(r, ...). - Change the three cut positions and the expected length to fit your layout. For an account string such as
6000-100-ZH, that would beLeft(ref, 4),Mid(ref, 6, 3),Right(ref, 2)andLen(ref) = 11. - If a piece is an identifier with leading zeros, add
ws.Range("D:D").NumberFormat = "@"before the line that writes the array to the sheet. - Step through the loop with
F8and watchrefandoutin the Locals window (View → Locals Window) to see each value being cut.
Range.Value returns and read data(r, 1) instead.Cut what is stored, not what you see
The lab lesson closes with the most expensive trap in text cutting, and it deserves a second look with an example. Left, Mid and Right need text. If you hand them a cell value that is a date or a number, VBA converts it to text first, and that conversion follows the computer's regional settings, not the cell's number format. A cell that shows 13 Sep 2026 holds a date. Left(cell.Value, 2) gives 9/ on a PC set to US formats and 13 on a PC set to UK formats. A cell that shows 1,234.50 holds 1234.5, so Right(cell.Value, 2) returns .5, not 50.
The reliable fix is to create the text yourself with a pattern you control, and then cut that:
Dim yearText As StringyearText = Left(Format(oneCell.Value, "yyyy-mm-dd"), 4) ' 2026 on every PC
.Text looks like a shortcut because it returns the displayed string, but it depends on column width and shows ##### when the column is too narrow. Format with an explicit pattern, or CStr for plain numbers, makes the result the same on every machine.
Changing text in place with the Mid statement
VBA has a feature the worksheet lacks: Mid can also stand on the left of an equals sign. Used that way it overwrites characters inside an existing String variable without building a new string:
Dim ref As Stringref = "CH-2026-04871"Mid(ref, 1, 2) = "DE"Debug.Print ref ' DE-2026-04871
The replacement never changes the length of the string: if you supply fewer characters than the length argument, only those are replaced, and extra characters are ignored. It is useful for masking, for example overwriting the middle digits of an account number with asterisks before a report is sent around, and it is a fast way to patch a fixed-width record.
Formulas, Flash Fill, Text to Columns or a macro?
Excel offers several ways to split a column, and it is worth knowing when a macro is the right choice. Flash Fill (Data → Flash Fill, or Ctrl+E) guesses a pattern from one or two examples you type. It is quick for a one-off job, but it produces fixed values, it can guess wrongly on unusual rows without telling you, and it does nothing when next week's export arrives. Text to Columns (Data → Text to Columns, with Fixed width or Delimited) is reliable for clean, uniform data, but it overwrites the columns to the right and also has to be repeated by hand. Worksheet formulas such as =LEFT(A2,2) update automatically and are transparent, which makes them ideal when other people need to follow the logic, but they add thousands of formulas to a large sheet.
A macro pays off when the same cleaning is repeated, when the data is too large to fill with formulas comfortably, or when you want rules that formulas express badly, such as "cut this way if the length is 13, write a note otherwise". The lab macro shows all three advantages in miniature: it runs in one keystroke, it writes values in a single block, and the length check turns an odd row into a visible note instead of a silent error. A practical habit is to prototype the cut with worksheet formulas on a few rows, confirm the positions, and then move the same numbers into Left, Mid and Right in VBA.

Common mistakes and how to spot them
- Counting from 0.
Mid(ref, 0, 2)raises run-time error 5. String positions start at 1; only arrays fromArray()andSplit()start at 0. If you see error 5 on aMidline, print the start position in the Immediate window. - Cutting values of different shapes at fixed positions. The result looks plausible and is wrong. Spot it by adding
=LEN(A2)next to the data and sorting or filtering by it; any length other than the expected one needs a different rule, orInStras in lesson 2. - Invisible spaces. A value copied from a web page may start with a space, so every cut is shifted by one.
Lenreturns one more than you expect. ApplyTrim$before cutting; lesson 3 deals with the non-breaking spaces thatTrim$leaves behind. - Losing leading zeros.
04871becomes 4871 in a General-formatted cell. Format the target column withNumberFormat = "@"before writing. - Cutting a date or number cell directly. The answer changes with the regional settings of whoever runs the macro. Convert with
Formatand an explicit pattern first. - Writing cell by cell inside the loop. It works, but it is slow on large columns. Collect the results in an array, as the lab does with
out, and write them with oneResize(...).Value = outstatement.
Quick reference
| VBA | Worksheet | Returns |
|---|---|---|
Left(text, n) | =LEFT(A2,n) | First n characters |
Right(text, n) | =RIGHT(A2,n) | Last n characters |
Mid(text, start, n) | =MID(A2,start,n) | n characters from position start (counting from 1) |
Mid(text, start) | no equivalent without a length | Everything from start to the end |
Len(text) | =LEN(A2) | Number of characters |
Mid(var, start, n) = "xx" | none | Overwrites characters inside a String variable |
Left$, Mid$, Right$ | none | Same as above, typed as String |
Format(value, "yyyy-mm-dd") | =TEXT(A2,"yyyy-mm-dd") | Text in a pattern you choose, safe to cut |
Alt+F11 · F5 · F8 · Ctrl+G | Editor · run · step · Immediate window |
Real-world uses
- Order and invoice references. Split references like the lab samples into country, year and number so you can pivot sales by country and year without asking IT for a new export.
- Chart-of-accounts strings. A general-ledger export with combined codes such as
6000-100-ZHbecomes three columns: account, cost centre and site, ready forSUMIFS. - Postcodes from address lines. In a column of Swiss addresses written as
8004 Zürich,Left(addr, 4)returns the postcode andMid(addr, 6)the town, provided every line follows that shape, which the length and a quick check of position 5 confirm. - Dates hidden in file names. For files named like
Sales_20261013.csv,Mid(fileName, 7, 8)extracts20261013, whichDateSerialcan then turn into a real date. - Fixed-width bank or legacy files. Older systems write records where every field has a fixed column range.
Midwith the documented start and length for each field turns each line into clean columns.
What you will build in the rest of this course
This first lesson is free. The six lessons that follow belong to the full course, a one-time purchase of $9.90, and each adds a technique you will use in real cleaning macros.
Finding Things: InStr and InStrRev. Instead of typing positions, you find them: the first hyphen, the last backslash in a path, the second occurrence of a separator. You also learn why every InStr result must be tested for zero before you cut with it, and how to count occurrences without a loop.
Trim, Case and Cleaning Up. The three Trim functions, why VBA's Trim is not the same as the worksheet TRIM, the non-breaking space that Trim cannot remove, and a reusable cleaner function you can drop into any project.
Split and Join. One line turns CH-2026-04871 into an array of three parts, whatever their lengths. You will limit the number of pieces, split multi-line cells apart and use the split-and-join round trip to reshape text.
Replace and the Like Operator. Swap or delete substrings everywhere at once, handle case sensitivity, and test values against patterns such as two letters, a hyphen and four digits, which is how you validate an entire column in a few lines.
Building Strings Efficiently. Why repeated & in a loop gets slow on large outputs, the built-in constants such as vbCrLf and vbTab, and how to collect pieces in an array and join them once to build a CSV line or a long report.
Format: Turning Values into Text. Numbers, percentages, dates and times turned into exactly the text you want, the difference between 0 and # in a pattern, and why minutes are nn and not mm in VBA.
Summary
Left, Mid and Right cut text by position, counting from 1, and Len tells you whether a value has the shape you expect. Always check the length before cutting at fixed positions, cut text you produced yourself rather than a date or number straight from a cell, and protect leading zeros when you write the results back. Now go back up to the lab, run SplitReferenceCodes, and confirm that five references are cut into three columns while CH-26-4871 is flagged. Then change the samples to a few values from your own work and adjust the three numbers.
Frequently asked questions
How do I extract part of a string in Excel VBA?
Use Left(text, n) for the first n characters, Right(text, n) for the last n, and Mid(text, start, n) for n characters from a position. Positions count from 1, and Len(text) returns the total length.
What is the difference between Mid in VBA and MID in Excel?
They count the same way, starting at 1. The VBA Mid function lets you leave out the length to get everything to the end, and VBA also has a Mid statement that overwrites characters inside a String variable.
What happens if Left or Mid asks for more characters than the string has?
Nothing breaks: VBA returns as many characters as exist, and a start position beyond the end returns an empty string. A start of 0 or a negative length raises run-time error 5.
What is the difference between Left and Left$ in VBA?
Left returns a Variant and Left$ returns a String. They give the same result for normal text, but Left$ raises an error when it receives Null, while Left passes the Null on.
Why does my macro lose the leading zeros when it writes text to a cell?
Excel interprets a string such as "04871" like typed input in a General-formatted cell and stores the number 4871. Set the target range to text with NumberFormat = "@" before writing the values.
Why does Left on a date cell give different results on different computers?
The cell holds a date, which VBA turns into text using the regional short-date setting before cutting it. Convert it yourself with Format(value, "yyyy-mm-dd") and cut that string to get the same result everywhere.
Keep going: Text & Strings
This free lab is lesson 1 of 7. Unlock the other 6 hands-on labs, the final exam and your certificate for a one-time CHF 9.90.
- Finding Things: InStr and InStrRev
- Trim, Case and Cleaning Up
- Split and Join
- Replace and the Like Operator
- Building Strings Efficiently
- Format: Turning Values into Text