How to split a string with multiple delimiters in vba excel?

Not allowed to comment (yet) but suggestion of using TRIM to eliminate a double space is not fully clear. The TRIM function in VBA only deletes leading and trailing spaces. It does not touch double spaces inside a string. You would have to use the worksheet function for that.


The previous answer is good, but will cause you to have trouble if there are back to back characters to be split on that are in the String, such as splitting "Hello, Sir! How are you doing, today?" on all punctuation and spaces. In this case, you would get a blank string between Hello and Sir.

To handle this scenario Chip Pearson provides a great VBA function for use: http://www.cpearson.com/excel/splitondelimiters.aspx


To split with several different delimiters ; list the delimiters in an array, replace them with a for loop, then split :

' New delimiter
tDelimNew = "myDelimiter"

' Replace each possible delimiter
For Each tDelimOld In Array(";", " ", ".", "<==", ":", vbCr)
    tString = Replace(tString, tDelimOld, tDelimNew)
Next tDelimOld

' Remove duplicate delimiters
tString = Replace(tString, tDelimNew & tDelimNew, tDelimNew)

' Split ;)
tResult = Split(tString , tDelimNew)

You could first do a Replace on the string first and then do the split:

newString = Replace(origString, "-", " ")
newArray = Split(newString, " ")

Tags:

Excel

Vba