VBA String Functions: Left, Mid, InStr, Replace, Split and More

VBA String Functions: Left, Mid, InStr, Replace, Split and More

📎 This article includes 1 downloadable practice file ↓

⏱ 4 min read

Exports from ERP systems, banks and web tools arrive full of text that needs fixing: codes with prefixes, names in capitals, extra spaces, “INV-2026-0045” where you only need the number. VBA’s string functions handle all of it, and once you know about a dozen of them you can clean almost anything.

In this article
  1. The core functions
  2. Find, then cut
  3. Split and Join
  4. Pattern checks with Like
  5. Format: numbers and dates to text
  6. A complete cleaning macro
  7. Where people go wrong
  8. Practice
  9. Continue learning

The core functions

Function Example Result
Len(s) Len("Delhi") 5
Left(s, n) Left("INV-0045", 3) INV
Right(s, n) Right("INV-0045", 4) 0045
Mid(s, start, n) Mid("27AAACR1234A1Z5", 3, 10) AAACR1234A (PAN inside a GSTIN)
InStr(s, find) InStr("ab@x.com", "@") 3
InStrRev(s, find) InStrRev("C:\a\b\file.xlsx", "\") 9
Replace(s, a, b) Replace("1,25,000", ",", "") 125000
Trim(s) Trim(" Ravi ") Ravi
UCase / LCase UCase("gstr") GSTR
StrConv(s, vbProperCase) StrConv("ASHA SHARMA", vbProperCase) Asha Sharma
💡 Versions with a dollar sign (Left$, Mid$, Trim$) return a String instead of a Variant — slightly faster and they error clearly on Null.

Find, then cut

Most real cleaning combines InStr with Left/Mid/Right:

Advertisement
email = "asha.sharma@company.in"
user   = Left$(email, InStr(email, "@") - 1)           ' asha.sharma
domain = Mid$(email, InStr(email, "@") + 1)            ' company.in

path = "D:\Reports\2026\October\Sales.xlsx"
fileName = Mid$(path, InStrRev(path, "\") + 1)          ' Sales.xlsx
folder   = Left$(path, InStrRev(path, "\"))             ' D:\Reports\2026\October\
⚠️ If the character isn’t there, InStr returns 0 and Left$(s, 0 - 1) errors. Check If InStr(s, "@") > 0 Then first.

Split and Join

Dim parts As Variant
parts = Split("Asha Sharma, Delhi, 110001", ",")
city = Trim$(parts(1))                 ' Delhi
pin  = Trim$(parts(UBound(parts)))     ' 110001
Debug.Print Join(parts, " | ")

Pattern checks with Like

If code Like "INV-####" Then ...                     ' INV- followed by 4 digits
If pan Like "[A-Z][A-Z][A-Z][A-Z][A-Z]####[A-Z]" Then ... ' PAN format
If name Like "*Pvt*Ltd*" Then ...                     ' contains both words

# is any digit, ? any character, * anything, [A-Z] a range.

Format: numbers and dates to text

Format(1250.5, "#,##0.00")           ' 1,250.50
Format(Date, "dd-mmm-yyyy")          ' 05-Oct-2026
Format(7, "000")                     ' 007  (leading zeros for codes)

A complete cleaning macro

Sub CleanCustomerList()
    Dim ws As Worksheet, r As Long, nm As String, gst As String
    Set ws = ThisWorkbook.Worksheets("Customers")
    For r = 2 To ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
        nm = Application.WorksheetFunction.Trim(ws.Cells(r, "A").Value)  ' also squeezes double spaces
        ws.Cells(r, "A").Value = StrConv(nm, vbProperCase)
        gst = UCase$(Replace(ws.Cells(r, "B").Value, " ", ""))
        ws.Cells(r, "B").Value = gst
        If Len(gst) = 15 Then
            ws.Cells(r, "C").Value = Mid$(gst, 3, 10)                   ' PAN
            ws.Cells(r, "D").Value = Left$(gst, 2)                      ' state code
        Else
            ws.Cells(r, "C").Value = "Check GSTIN"
        End If
    Next r
End Sub

Note WorksheetFunction.Trim: VBA’s own Trim removes spaces only at the ends, while Excel’s TRIM also turns double spaces inside the text into single ones.

Where people go wrong

  • Invisible characters — non-breaking spaces (Chr(160)) from web copies aren’t removed by Trim. Replace(s, Chr(160), " ") first.
  • Numbers stored as text after cleaning — convert with CDbl() or Val() before writing back.
  • Case-sensitive InStr — pass vbTextCompare: InStr(1, s, "gst", vbTextCompare).

Practice

The workbook has a messy customer export (names in capitals, spaces inside GSTINs, emails, file paths) and buttons for each cleaning step, with expected results to compare against.

Next: arrays — the technique that makes all of these macros dramatically faster.

⚡ Interactive Practice Lab & Formula Tester:

Test formulas dynamically in our web formula laboratory or download the companion Excel workbook.

📎 Practice files for this article

  • 📗
    Practice workbook with all course macros (.xlsm)Open it, click Enable Content in the yellow bar, go to the Macros sheet and press any button. 60 sales rows included to test on.
    ⬇ XLSM · 29 KB

Free to use for learning. Files with macros (.bas) are plain text — import them with Alt+F11 → File → Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free · AI can be wrong

Leave a Reply

Your email address will not be published. Required fields are marked *