Smart Systems for Home

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

Excel VBA Parse String: Split Text in Cells

· 7 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

You parse a string in Excel VBA with the Split function when you know the delimiter, with InStr/InStrRev plus Mid when the separator position matters, and with RegExp when the pattern is irregular. The common case — turning Doe, Jane, jane@example.com into three fields — takes four lines of Split. Click into the Visual Basic Editor, paste a small test macro, and run it on a throwaway sheet before you point it at real data.

What You'll Need

  • Excel on Windows or Mac with macros enabled; the Visual Basic Editor opens with Alt+F11 on Windows and Option+F11 on a Mac.
  • A worksheet with sample strings in column A, including one deliberately messy row (double spaces, a missing field, trailing comma).
  • A workbook saved as .xlsm, since a standard .xlsx cannot store macros.
  • Optional: a reference to Microsoft VBScript Regular Expressions set in Tools > References, only if you plan on the pattern-matching route.

Step-by-Step

  1. Save a copy of your workbook first. Parsing macros usually overwrite the column they read. Work on a duplicate so the original text stays intact.
  2. Open the editor and insert a module. Press Alt+F11 (Option+F11 on Mac), then Insert > Module. Code typed into a sheet's own module also works but is harder to reuse.
  3. Write a macro that reads one cell. Start with a single value so you can watch the output:
    Sub ParseOne()
      Dim src As String
      src = "Doe, Jane, jane@example.com"
      Dim parts() As String
      parts = Split(src, ",")
      Debug.Print UBound(parts), parts(0), parts(1)
    End Sub

    Press F5 and check the Immediate Window (Ctrl+G) for the count and the first two pieces.
  4. Trim the results. Split keeps the spaces after each comma, so run each part through Trim: parts(1) = Trim(parts(1)). Without this, " Jane" will not match "Jane" in a lookup.
  5. Loop over a whole column. Replace the hard-coded string with a loop from row 2 to the last used row: find that row with Cells(Rows.Count, "A").End(xlUp).Row, then write parts across columns B, C and D with Cells(r, 2).Value = parts(0) and so on.
  6. Guard against missing fields. If a row has fewer delimiters than expected, UBound(parts) is lower than your column count and parts(2) throws error 9 (subscript out of range). Test before you write: If UBound(parts) >= 2 Then Cells(r, 4).Value = parts(2), otherwise write an empty value or a flag.
  7. Handle multiple delimiters. Split accepts exactly one separator string. For strings that might use commas or pipes, test with InStr first and choose the delimiter before splitting, or normalise with Replace: src = Replace(src, "|", ","). Collapse repeated spaces with a loop or WorksheetFunction.Trim, which strips doubles that plain Trim leaves behind.
  8. Pull a field by position when there is no clean delimiter. Use InStr to find the first colon, Mid to read everything after it, and InStrRev to find the last dot if you need an extension. Example: path = Mid(s, InStrRev(s, "\") + 1) returns the file name from a full path.
  9. Use a regular expression for irregular text. With the RegExp reference set, create objRegEx, set .Pattern to something like "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", set .Global = True, and loop the Matches collection to collect every email address regardless of surrounding text. Test the pattern against your messiest row before trusting it.
  10. Write results to a new area, not over the source. Output to columns B onward, or to a second worksheet, and add a header row so the result is readable. Clear the output range at the top of the macro so a rerun does not leave stale values behind.
  11. Harden the loop before running it on everything. Switch off screen updating (Application.ScreenUpdating = False) and restore it at the end, wrap the body in error handling that logs the failing row number, and add On Error GoTo 0 after your handler so later errors are not swallowed silently.
  12. Test on the messy rows. An empty cell, a single-field cell, a cell with only the delimiter, and a cell holding numbers that Excel has already converted to dates. Fix what breaks, then run on the full column.

Common Mistakes

Assigning a Split result to a String. Split returns a zero-based array; declaring Dim x As String and assigning to it raises a type mismatch. Declare Dim parts() As String.

Forgetting that arrays start at zero. parts(0) is the text before the first delimiter, not parts(1). Off-by-one errors here silently shift every column by one.

Trusting the delimiter count. A missing trailing comma means the last field disappears rather than arriving empty. Always check UBound.

Parsing numbers. Values like 01/02 or 1-2 may already be dates by the time VBA sees them. Read with .Text instead of .Value, or set the source cells to Text format, when leading zeros or exact characters matter.

Leaving stale output. Rerunning a macro without clearing the target range leaves old values in rows that now have fewer fields.

Tips

Use Split with a limit argument — Split(s, ",", 2) — when everything after the first delimiter belongs together, such as a name followed by free-text notes containing commas.

Name your array bounds check once: n = UBound(parts) then test r <= n or n >= 2, rather than repeating the call.

For tab-separated or CSV files that arrive as text files, Workbooks.Open with the delimiter argument, or the Data > From Text/CSV route, is usually faster and safer than parsing in VBA. Save VBA parsing for text already sitting inside cells.

Keep a helper function that takes a string and a delimiter and returns the nth field. It saves repeating the bounds checks in every macro and makes fixes one-line.

Comment the expected format at the top of each macro. Six months later the delimiter rules are never obvious from the code.

Troubleshooting

Error 9, subscript out of range. You indexed a part that does not exist. Print UBound(parts) for the failing row, then add the bounds check.

Error 13, type mismatch. Either you assigned the array to a non-array variable, or the cell holds an error value such as #N/A. Test with IsError before parsing.

Results look right but lookups fail. Invisible characters are the usual cause: non-breaking spaces (Chr(160)), line breaks (Chr(10)) or trailing spaces. Clean with Replace(Replace(s, Chr(160), " "), Chr(10), " ") then WorksheetFunction.Trim.

The macro stops partway. One row triggered an error and the loop has no handler. Add On Error GoTo with a handler that records the row number and resumes at the next row.

The regular expression never matches. Check the pattern against a single literal string in the Immediate Window first, confirm .Global is set to True for all matches, and confirm the VBScript RegExp reference is ticked.

Nothing happens at all. Macros may be disabled, or the code sits in a sheet module while you are calling it from elsewhere. Check the Trust Center macro settings and that the Sub is Public.

If that did not work, strip the macro back to one cell with a literal string, confirm it prints correctly, then reintroduce the loop and the real range one piece at a time.

Frequently Asked Questions

Can I split a string on more than one delimiter at once?

Not directly. Split takes a single separator. Replace the secondary delimiters with the primary one first, then split, or use a regular expression.

How do I get the second item from a comma-separated string?

Split(s, ",")(1) returns it. Remember the array is zero-based, so index 1 is the second element, and wrap it in Trim.

Does Split work the same on Mac Excel?

Yes, Split, InStr and Mid behave identically. The editor shortcut differs (Option+F11) and older Mac builds may lack some Windows-only libraries, but the VBScript RegExp reference is available on modern Mac Excel.

Can I parse an entire column without a loop?

No. Excel has no array formula equivalent of Split inside VBA. A loop over rows is the standard approach; for very large ranges, reading the column into a variant array first is much faster than cell-by-cell access.

How do I handle empty fields between delimiters?

Split preserves them: "a,,c" gives three elements with an empty string in the middle. That empty string is a real element, so your bounds check still passes.

Why does my parsed date or number look different?

Excel may have already converted the cell to a date or number before VBA saw the text. Read .Text or store the source as text to keep the exact characters.