Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel VBA Substring: Mid, Left, Right & InStr

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

There is no single Substring function in Excel VBA. Instead you use three built-in string functions: Left returns characters from the start, Right returns characters from the end, and Mid returns characters from any position you specify. To find where a substring begins, use InStr or InStrRev. Combine them and you can extract almost any piece of text.

What You'll Need

  • Excel on Windows or Mac (the VBA editor is included in both).
  • A workbook saved as .xlsm if you want to keep macros, or .xlsx if you only need to test in the editor.
  • Basic familiarity with opening the VBA editor (Alt+F11 on Windows; on Mac, use the Developer tab or Tools > Macro > Visual Basic Editor).
  • Sample text in a cell, for example Smart-Home-Camera-2024 in A1, so you can see results immediately.

Step-by-Step

  1. Open the VBA editor. Press Alt+F11 (Windows) or use the Developer tab (Mac). If the Developer tab is hidden, enable it in Excel Options > Customize Ribbon. Menu labels can differ slightly by version and platform.
  2. Insert a module. In the editor, choose Insert > Module. This is where your code will live.
  3. Understand the syntax before writing. The three functions take these arguments:
    • Left(text, length) – returns the first length characters.
    • Right(text, length) – returns the last length characters.
    • Mid(text, start, length) – returns length characters beginning at position start. The length argument is optional; if omitted, Mid returns everything from start to the end.
    • InStr(start, text, substring) – returns the position of the first occurrence, or 0 if not found. InStrRev(text, substring) searches from the end.
  4. Write a basic Left example. In the module, type:
    Sub ShowLeft()
        Dim s As String
        s = "Smart-Home-Camera-2024"
        MsgBox Left(s, 5)   ' returns "Smart"
    End Sub
    Press F5 to run it. A message box should show Smart.
  5. Write a Right example. Add:
    Sub ShowRight()
        Dim s As String
        s = "Smart-Home-Camera-2024"
        MsgBox Right(s, 4)  ' returns "2024"
    End Sub
    Run it. The year appears.
  6. Write a Mid example. Add:
    Sub ShowMid()
        Dim s As String
        s = "Smart-Home-Camera-2024"
        MsgBox Mid(s, 7, 4)  ' returns "Home"
    End Sub
    Position 7 is the H in Home; length 4 grabs H-o-m-e.
  7. Find a substring with InStr. Add:
    Sub FindPart()
        Dim s As String, pos As Long
        s = "Smart-Home-Camera-2024"
        pos = InStr(s, "Camera")
        MsgBox pos   ' returns 12
    End Sub
    If the substring is not present, InStr returns 0, so always test for that before using Mid.
  8. Combine InStr and Mid for dynamic extraction. To pull the text between two hyphens:
    Sub ExtractBetween()
        Dim s As String, firstPos As Long, secondPos As Long
        s = "Smart-Home-Camera-2024"
        firstPos = InStr(s, "-")
        secondPos = InStr(firstPos + 1, s, "-")
        If firstPos > 0 And secondPos > 0 Then
            MsgBox Mid(s, firstPos + 1, secondPos - firstPos - 1)  ' returns "Home"
        End If
    End Sub
    The second InStr starts searching after the first hyphen, which prevents it from finding the same one again.
  9. Read from a cell and write back. To apply this to real data:
    Sub ExtractFromCell()
        Dim s As String
        s = Range("A1").Value
        Range("B1").Value = Mid(s, 1, 5)
    End Sub
    This puts the first five characters of A1 into B1.
  10. Test edge cases. Try an empty cell, a string shorter than your length argument, and a substring that does not exist. Left, Right and Mid handle short strings gracefully (they return what is available), but InStr returns 0. Add guards like If Len(s) >= 5 Then when it matters.

Common Mistakes

  • Using a zero or negative length. Left, Right and Mid with a length of 0 return an empty string; negative values raise an error.
  • Forgetting that Mid's start position is 1-based. Position 1 is the first character, not 0 as in many other languages.
  • Not checking InStr for 0. If the substring is missing, InStr returns 0, and passing 0 into Mid causes a run-time error.
  • Mixing up InStr argument order. The signature is InStr([start], string1, string2). Putting the substring first silently searches the wrong way.
  • Assuming case sensitivity. By default InStr is case-sensitive. Use vbTextCompare as the fourth argument if you need a case-insensitive search.
  • Expecting a Substring function to autocomplete. It does not exist; typing Substring( will not work.

Tips

  • Use Len(s) to get the total length, which is handy when calculating how many characters to take from the right.
  • Use InStrRev to find the last occurrence of a delimiter, such as the final backslash in a file path.
  • Wrap repeated extraction logic in your own function, for example Function Between(s As String, a As String, b As String) As String, so you can reuse it across modules.
  • Use Trim after extraction if your source text may contain leading or trailing spaces.
  • For very long strings or many rows, read the range into a Variant array and process in memory rather than writing cell by cell; it is dramatically faster.
  • Comment your position math. Off-by-one errors in Mid are the most common source of bugs.

Troubleshooting

  • Run-time error 5 (Invalid procedure call or argument): usually a negative length or a start position of 0 in Mid. Check your variables with a MsgBox before the failing line.
  • Run-time error 13 (Type mismatch): the value you passed is not a string, often because a cell contains an error value. Test with IsError first.
  • Result is blank: the length argument may exceed the string length, or the start position may be past the end. Print Len(s) and your positions to confirm.
  • InStr always returns 0: check case and hidden spaces. Use vbTextCompare and Trim.
  • Macros will not run: confirm the file is saved as .xlsm and that macro security settings allow macros. Do not lower security settings permanently; use a trusted location instead.
  • If that did not work: step through the code with F8 to watch each variable, and use the Immediate Window (Ctrl+G) to print values with ? s.

Frequently Asked Questions

Is there a Substring function in VBA?

No. VBA uses Left, Right and Mid for substring extraction, plus InStr and InStrRev to locate positions.

How do I get the last N characters of a string?

Use Right(s, n). For example, Right("Camera-2024", 4) returns "2024".

How do I extract text between two characters?

Find both positions with InStr, then use Mid with a start of the first position plus one and a length equal to the gap between them minus one.

Is InStr case-sensitive?

Yes by default. Add vbTextCompare as the fourth argument for a case-insensitive search.

What happens if Mid's length is omitted?

Mid returns everything from the start position to the end of the string.

Can I use these functions on a range of cells?

Yes, but loop through the cells or load the range into an array first. Writing results cell by cell is slow on large ranges.