Tabellab

Cutting Text: Left, Mid and Right

Lesson 1 of 7Reading

Three functions, one idea

Every text-cleaning job starts the same way: take a piece out of a longer string. VBA gives you three functions for it, and they behave exactly like their worksheet cousins.

  • Left(text, n) — the first n characters.
  • Right(text, n) — the last n characters.
  • Mid(text, start, n) — n characters beginning at position start, counting from 1. Leave n off and you get everything to the end.
  • Len(text) — how many characters there are altogether.
Sub CutParts()
    Dim ref As String

    ref = "CH-2026-04871"

    Debug.Print Left(ref, 2)      ' CH
    Debug.Print Mid(ref, 4, 4)    ' 2026
    Debug.Print Right(ref, 5)     ' 04871
    Debug.Print Mid(ref, 4)       ' 2026-04871
    Debug.Print Len(ref)          ' 13
End Sub

A macro you can run right now

This one needs nothing prepared: it builds its own sample sheet, splits a column of reference codes into three columns, and flags anything that does not fit the expected shape. Open the VBA editor with Alt+F11, choose Insert → Module, paste the code in and press F5.

Option Explicit

Sub SplitReferenceCodes()
    Dim ws As Worksheet
    Dim samples As Variant
    Dim out() As Variant
    Dim ref As String
    Dim r As Long

    samples = Array("CH-2026-04871", "DE-2026-11250", "CH-2025-00042", _
                    "AT-2026-93117", "CH-26-4871", "FR-2026-70008")

    On Error Resume Next
    Set ws = ThisWorkbook.Worksheets("Ref Demo")
    On Error GoTo 0

    If ws Is Nothing Then
        Set ws = ThisWorkbook.Worksheets.Add( _
            After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))
        ws.Name = "Ref Demo"
    End If

    ws.Cells.Clear
    ws.Range("A1:D1").Value = Array("Reference", "Country", "Year", "Number")
    ws.Range("A1:D1").Font.Bold = True

    ReDim out(1 To UBound(samples) + 1, 1 To 4)

    For r = 0 To UBound(samples)
        ref = CStr(samples(r))
        out(r + 1, 1) = ref

        If Len(ref) = 13 Then
            out(r + 1, 2) = Left(ref, 2)
            out(r + 1, 3) = Mid(ref, 4, 4)
            out(r + 1, 4) = Right(ref, 5)
        Else
            out(r + 1, 2) = "CHECK: " & Len(ref) & " characters"
        End If
    Next r

    ws.Range("A2").Resize(UBound(out, 1), 4).Value = out
    ws.Columns("A:D").AutoFit
    ws.Activate
End Sub

Line by line

  • samples = Array(...) keeps the test data inside the macro, so there is nothing to download. Later you replace this one line with a read from your own column.
  • The On Error Resume Next pair asks whether the sheet already exists without stopping the macro when it does not; If ws Is Nothing then creates it. This get-or-create block appears in almost every macro you will write.
  • ReDim out(1 To UBound(samples) + 1, 1 To 4) — one row per sample, four columns. Array() counts from 0 and the sheet counts from 1, which is where the + 1 comes from.
  • If Len(ref) = 13 is the guard. Cutting at fixed positions is only correct while every value has exactly the same shape.
  • Left(ref, 2), Mid(ref, 4, 4), Right(ref, 5) pull out country, year and number. To fit your own layout you change these three numbers and nothing else.
  • The Else branch writes what is wrong and how long the value really was, instead of silently producing a wrong year.
  • ws.Range("A2").Resize(...).Value = out writes the whole block in one go, which is far quicker than filling cell by cell.
  • ThisWorkbook means the workbook that holds the code. If you keep your macros in PERSONAL.XLSB, swap it for ActiveWorkbook or the sheet appears in the hidden personal file.

The trap: you cut what is stored, not what you see

Left, Mid and Right want text. Hand them a cell and VBA converts the cell's underlying value to text first — and that value is rarely the string on screen. A cell showing 13 Sep 2026 holds a date, so Left(oneCell.Value, 2) returns whatever your Windows short-date setting produces: 9/ in Chicago, 13 in London. A cell showing 1,234.50 holds the number 1234.5.

Dim oneCell As Range

Set oneCell = ThisWorkbook.Worksheets("Ref Demo").Range("A2")

Debug.Print Left(oneCell.Value, 2)                        ' the stored value
Debug.Print Left(oneCell.Text, 2)                         ' what is displayed
Debug.Print Left(Format(oneCell.Value, "yyyy-mm-dd"), 4)  ' what you meant

.Text looks like the fix and then costs you the afternoon: it returns exactly what the cell displays, so on a column too narrow for a date or a number it hands you #####. Column widths are not a data format. Cut a string you produced yourself — Format() with a pattern you chose, or CStr() — and the machine it runs on stops mattering.

Test Len() before you cut at fixed positions. One length check turns a silent wrong answer into a visible note somebody can go and look at.

How this course goes on

Fixed positions hold up only as long as the data does. Lesson 2 finds the separator with InStr, so the cutting position comes out of the text itself instead of being typed in; lesson 4 cuts on every separator at once with Split. The rest of the course covers stripping stray spaces and non-printing characters, swapping substrings with Replace, pattern-matching with Like, joining thousands of pieces without the usual slowdown, and turning numbers and dates back into formatted text with Format.

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.

Cutting "CH-2026-04871" by position (counting starts at 1) pos 1C2H3-425062768-90104118127131 Left(ref, 2) = CH Mid(ref, 4, 4) = 2026 Right(ref, 5) = 04871 Mid(ref, 4) = 2026-04871 (no length: to the end) Len(ref) = 13 separators at positions 3 and 8 are never cut out
Positions in the lab reference. The country sits in positions 1 to 2, the year in 4 to 7 and the running number in 9 to 13. Mid without a length returns everything from the start position to the end.

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 String
ref = "CH-2026-04871"
Debug.Print Left(ref, 2) ' CH
Debug.Print Mid(ref, 4, 4) ' 2026
Debug.Print Right(ref, 5) ' 04871
Debug.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-0487113CH202604871CH
DE-2026-1125013DE202611250DE
CH-2025-0004213CH202500042CH
AT-2026-9311713AT202693117AT
CH-26-487110not cut: "CHECK: 10 characters"CHECK: 10 characters
FR-2026-7000813FR202670008FR

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.

Len(ref) for the six lab samples: the guard before cutting expected length 13 CH-2026-0487113DE-2026-1125013CH-2025-0004213AT-2026-9311713CH-26-487110FR-2026-7000813 051013 cut into three columns "CHECK: 10 characters"
Len for each sample. Five references have the expected 13 characters and are cut; CH-26-4871 has only 10, so the macro writes a note instead of a wrong year.

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

  1. Save the workbook as an Excel Macro-Enabled Workbook (.xlsm) via File → Save As, or the code will not be kept.
  2. Press Alt+F11 to open the Visual Basic Editor, then choose Insert → Module.
  3. Paste the complete SplitReferenceCodes listing from the lab, click anywhere inside it and press F5. A sheet called Ref Demo appears with four columns.
  4. Press Ctrl+G for the Immediate window and try a few cuts yourself, for example ?Mid("CH-2026-04871", 9), which prints 04871.
  5. To process your own column instead of the built-in samples, replace the samples = Array(...) line with a read from the sheet, for example samples = Application.Transpose(Worksheets("Orders").Range("A2:A500").Value), Because that array starts at 1 rather than 0, also change the loop to For r = 1 To UBound(samples), the sizing line to ReDim out(1 To UBound(samples), 1 To 4), and every out(r + 1, ...) to out(r, ...).
  6. Change the three cut positions and the expected length to fit your layout. For an account string such as 6000-100-ZH, that would be Left(ref, 4), Mid(ref, 6, 3), Right(ref, 2) and Len(ref) = 11.
  7. 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.
  8. Step through the loop with F8 and watch ref and out in the Locals window (View → Locals Window) to see each value being cut.
Application.Transpose is handy for a single column, but it has limits on very large ranges in older Excel versions. For big exports, keep the two-dimensional array that 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 String
yearText = 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 String
ref = "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.

Illustration for the Tabellab course Text and Strings in Excel VBA
Text & Strings: cut, search, split, join and reshape messy text until it looks like clean data.

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 from Array() and Split() start at 0. If you see error 5 on a Mid line, 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, or InStr as in lesson 2.
  • Invisible spaces. A value copied from a web page may start with a space, so every cut is shifted by one. Len returns one more than you expect. Apply Trim$ before cutting; lesson 3 deals with the non-breaking spaces that Trim$ leaves behind.
  • Losing leading zeros. 04871 becomes 4871 in a General-formatted cell. Format the target column with NumberFormat = "@" before writing.
  • Cutting a date or number cell directly. The answer changes with the regional settings of whoever runs the macro. Convert with Format and 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 one Resize(...).Value = out statement.

Quick reference

VBAWorksheetReturns
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 lengthEverything from start to the end
Len(text)=LEN(A2)Number of characters
Mid(var, start, n) = "xx"noneOverwrites characters inside a String variable
Left$, Mid$, Right$noneSame 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+GEditor · 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-ZH becomes three columns: account, cost centre and site, ready for SUMIFS.
  • Postcodes from address lines. In a column of Swiss addresses written as 8004 Zürich, Left(addr, 4) returns the postcode and Mid(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) extracts 20261013, which DateSerial can then turn into a real date.
  • Fixed-width bank or legacy files. Older systems write records where every field has a fixed column range. Mid with 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 $9.90.

  1. Finding Things: InStr and InStrRev
  2. Trim, Case and Cleaning Up
  3. Split and Join
  4. Replace and the Like Operator
  5. Building Strings Efficiently
  6. Format: Turning Values into Text

Buy course — $9.90 See the full course

Knowledge check

What does Mid("INVOICE-2026", 9, 4) return?

Continues in this course
  • 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

Buy the course to unlock the remaining 6 lessons, the exam and the certificate.

Buy course — $9.90