Delimiter in excel vba

Introduction

The VBA Split Function is used is to split a string of text into an array. The text is split based on a given delimiter – e.g. a comma, space, colon etc.

For example, imagine we have the following string:

“Apple:Orange:Pear:Plum”

You can see that each item separated by the colon sign. We call the colon sign the delimiter.

We can split this string into an array:

' https://excelmacromastery.com/
Sub SplitBasic()

    Dim arr() As String
    arr = Split("John:Jane:Paul:Sophie", ":")

End Sub

Once it is in an array it is easy to access each item:

VBA Split

Glossary

Array – a structure for storing a group of similar variables.

Ubound – this function gives the last position of an array.

Lbound – this function gives the first position of an array. For an array, returned by the Split function, the first position is zero.

Instr – this function is used to search for a string within a string and return the position.

InStrRev – the same as Instr but searches a string from the end.

Split Syntax

Split expression, delimiter[optional], limit[optional], compare[optional]

Split Return Value

The Split function returns an array.

 Split Function Parameters

expression – this is the text string that is to be split.

delimiter [optional] – the character delimiter used in the string to separate each item. If you don’t use this parameter then VBA uses space as the delimiter.

limit [optional] – this allows us to set the number of items in the result. If we use 1 as the limit then no split takes place and the full string is returned.

compare [optional] – if we are using letters as the delimiter then this determines if we take the case of letters into consideration.

VBA Split – Simple Example

The following code shows an example of using the Split function and printing the result to the Immediate Window:

' https://excelmacromastery.com/
Sub VBA_Split_Print()

    Dim arr() As String
    ' Split the string to an array
    arr = Split("John:Jane:Paul:Sophie", ":")

    ' Print each item in the array to the Immediate Window(Ctrl + G)
    Dim name As Variant
    For Each name In arr
        Debug.Print name
    Next

End Sub

Output
John
Jane
Paul
Sophie

When we split the string into an array we have an item in each position in the array. This means we can easily access any item using the array position:

' https://excelmacromastery.com/
Sub VBA_Split_PrintArr()

    Dim arr() As String
    ' Split the string to an array
    arr = Split("John:Jane:Paul:Sophie", ":")

    Debug.Print arr(0) ' Print John
    Debug.Print arr(1) ' Print Jane
    Debug.Print arr(2) ' Print Paul
    Debug.Print arr(3) ' Print Sophie

End Sub

Split returns an array that starts at position zero. If we want to use a For statement to read through the array we can use LBound and UBound to give us the first and last positions of the array:

' https://excelmacromastery.com/
Sub VBA_Split_Print()

    Dim arr() As String
    ' Split the string to an array
    arr = Split("John:Jane:Paul:Sophie", ":")

    ' Print each item in the array to the Immediate Window(Ctrl + G)
    Dim i As Long
    For i = LBound(arr) To UBound(arr)
        Debug.Print arr(i)
    Next

End Sub

Split Limit Parameter

The Limit parameter is used to determine how items are placed in the array. In other words, how many items is the original string split into.

The table below shows the results of using different limits this sample string:

String Limit Result
«John:Jane:Paul:Sophie» 1 John:Jane:Paul:Sophie
«John:Jane:Paul:Sophie» 2 John
Jane:Paul:Sophie
«John:Jane:Paul:Sophie» 3 John
Jane
Paul:Sophie
«John:Jane:Paul:Sophie» 4 John
Jane
Paul
Sophie

You can try out the code for yourself:

' https://excelmacromastery.com/
Sub VBA_Split_Limit()

    Dim arr() As String
    ' Split the string to an array
    arr = Split("John:Jane:Paul:Sophie", ":", 1)

    ' Print each item in the array to the Immediate Window(Ctrl + G)
    Dim name As Variant
    For Each name In arr
        Debug.Print name
    Next

End Sub

Split Compare Parameter

The Compare parameter is used for delimiters that are made up of one or letters.

For example, imagine we want to use the letter x as a delimiter in the following string:

“12x34X45x”

  1. If we want to split by x when lower case only – then we use vbBinaryCompare.
  2. If we want to split by upper or lower case – then we use vbTextCompare.
  3. vbUseCompareOption is the default and tells split to use the module Compare settings. Read more about the module compare settings here.

The following code shows how we use the Compare parameter:

' https://excelmacromastery.com/
Sub VBA_Split_Compare()

    Dim arr() As String
    ' Split the string to an array - not case sensitive
    arr = Split("12x34X45", "x", , vbTextCompare)

    ' Print each item in the array to the Immediate Window(Ctrl + G)
    Dim name As Variant
    For Each name In arr
        Debug.Print name
    Next

End Sub

The following table shows the results from the different Compare arguments:

String Delimiter Compare Type Result
«12x34X45» x vbCompareText 12
34
45
«12x34X45» x vbCompareBinary 12
34X45

Reversing Split

We can use the Join function to do the opposite of what the split function does. Join converts an array into a string and adds a given delimiter.

This can be useful as sometimes we may want to split a string, update one or more values in the array and then convert the array to a string.

This example shows how to use Join:

' https://excelmacromastery.com/
Sub UsingJoin()

    Dim arr As Variant
    
    ' create an array using the array function
    arr = Array("Apple", "Orange", "Pear")
    
    Dim s As String
    ' Covert the array to a string using the colon delimiter
    s = Join(arr, ":")
    
    ' Print the string to the Immediate Window(Ctrl + G)
    Debug.Print s

End Sub

See the section “Split Example – Using Join” for an example of using the Join function with the Split function.

Split Example – Names

A really great example of Split is when dealing with names.

Imagine we have the name “John Henry Smith” and we want to extract each name.

We can use Left and Instr to get the first name:

' https://excelmacromastery.com/
Sub Instr_Firstname()
    
    Dim s As String
    s = "John Henry Smith"
    
    ' Get the position of the first space
    Dim position As Long
    position = InStr(s, " ") - 1

    ' Prints John
    Debug.Print Left(s, position)

End Sub

To get the last name is a bit trickier:

' https://excelmacromastery.com/
Sub Instr_Lastname()
    
    Dim s As String
    s = "John Henry Smith"
    
    ' Get the position of the last space
    Dim position As Long, length As Long
    position = InStrRev(s, " ") - 1
    length = Len(s)
    
    ' Prints Smith
    Debug.Print Right(s, length - position)

End Sub

Getting names that are not in the first or last position gets very messy indeed. However,  using Split we can simplify the whole process:

' https://excelmacromastery.com/
Sub SplitName()

    Dim s As String: s = "John Henry Smith"
    
    Dim arr() As String
    
    arr = Split(s, " ")
    Debug.Print arr(0) ' John
    Debug.Print arr(1) ' Henry
    Debug.Print arr(2) ' Smith

End Sub

We actually don’t need to use an array as we can see in the next example. It is not efficient to call the Split function 3 times instead of 1 but it does look nice in this example:

' https://excelmacromastery.com/
Sub SplitName()

    Dim s As String: s = "John Henry Smith"
    
    Debug.Print Split(s, " ")(0) ' John
    Debug.Print Split(s, " ")(1) ' Henry
    Debug.Print Split(s, " ")(2) ' Smith

End Sub

Split Example – Filenames

In the next example we use Split to get the extension part of a filename:

' https://excelmacromastery.com/
Sub GetFileExt()

    ' Create an array of filenames for our test
    Dim myFiles As Variant
    myFiles = Array("my resume.xlsx", "myresume2.doc", "my resume latest ver.pdf")

    Dim file As Variant, arr() As String
    ' Read through the filenames
    For Each file In myFiles
        ' Split by the period
        arr = Split(file, ".")
        ' Use Ubound to get the last position in the array
        Debug.Print arr(UBound(arr))
    Next file

End Sub

Here is an interesting one you can try for yourself. Given a full file name, try to write code to extract the filename without the extension or folder.

For example for “C:MyDocsJanMyResume.Doc” we want to extract MyResume.

' https://excelmacromastery.com/
Sub GetFilenamePart()

    ' Create an array of filenames for our test
    Dim myFiles As Variant
    myFiles = Array("C:MyDocsJanMyResume.Doc" _
                , "C:MyMusicSongslovesong.mp3" _
                , "D:MyGamesGamesSavedsavedbattle.sav")

    Dim file As Variant, arr() As String
    ' Read through the filenames
    For Each file In myFiles
        
        ' Split by the period
        arr = Split(file, ".")
        
        ' Split by the folder separator /
        arr = Split(arr(0), Application.PathSeparator)
        
        Debug.Print arr(UBound(arr))
    
    Next file

End Sub

Output

MyResume
lovesong
savedbattle

Split Example – Copy to a Range

Because the result of Split is an array, we easily copy it to a range.

' https://excelmacromastery.com/
Sub VBA_Split_Range()

    Dim s As String
    s = "001,John Smith,New York,067435334"
    
    ' write the values to cells A1 to D1
    Sheet1.Range("A1:D1").Value = Split(s, ",")
    
    ' write the values to cells A1 to A4
    Sheet1.Range("A1:A4").Value = WorksheetFunction.Transpose(Split(s, ","))

End Sub

Split Example – Count Items

If we want to count the number of items in a delimited string we can use Split to do this for us.

We simply split the string and then use the Ubound function to give us back the number of items. We saw already that UBound is used to give us back the last position in an array. Because, the array start at zero, we need to add one to get the number of items.

' https://excelmacromastery.com/
Sub Split_Count()
    
    Dim s As String
    s = "Apple,Orange,Mango,Peach,Plum,Banana,Pear"

    Debug.Print "number of items:" & UBound(Split(s, ",")) + 1

End Sub

Split Example – Using Join

This is an interesting one that you may want to try yourself. Take the three strings below:

123.3456.96.345
1234.1156.7.345
1273.9998.123.345

We want to add one to the third number in each string. For example, the first string should become  123.3456.97.345.

Before you try yourself, I will give one hint. You can use the Join function to reverse the Split operation. It takes a array and delimiter and creates a string.

You can start with this code:

' https://excelmacromastery.com/
Sub UpdateNumber()

    ' Create an array of number for our test
    Dim myNums As Variant
    myNums = Array("123.3456.99.345" _
                , "1234.1156.7.98" _
                , "1273.9998.123.3235")

    ' Read through the strings
    Dim i As Long, arr() As String
    For i = LBound(myNums) To UBound(myNums)
        
        ' add your code here

    Next i
    
    ' Print the updated array to the Immediate Window(Ctrl+G)
    Debug.Print vbNewLine & "Printing new array"
    For i = LBound(myNums) To UBound(myNums)
        Debug.Print myNums(i)
    Next i

End Sub

This is how to do it:

' https://excelmacromastery.com/
Sub UpdateNumber()

    ' Create an array for our test
    Dim myNums As Variant
    myNums = Array("123.3456.99.345" _
                , "1234.1156.7.98" _
                , "1273.9998.123.3235")

    ' Read through the strings
    Dim i As Long, arr() As String
    For i = LBound(myNums) To UBound(myNums)
        
        ' Split the string to an array
        arr = Split(myNums(i), ".")
        
        ' Add one to the number
        arr(2) = arr(2) + 1
        
        ' convert the array back to a string
        myNums(i) = Join(arr, ".")

    Next i
    
    ' Print the updated array to the Immediate Window(Ctrl+G)
    Debug.Print vbNewLine & "Printing new array"
    For i = LBound(myNums) To UBound(myNums)
        Debug.Print myNums(i)
    Next i

End Sub

 Output

123.3456.100.345
1234.1156.8.345
1273.9998.124.345

Further Reading

The Ultimate Guide to VBA String Functions

Extracting using the Split function

VBA Arrays

VBA For Loop

Microsoft Docs – Split function

If you would like to see some real-world examples of using Split, you will find them in the post How to Easily Extract From Any String Without Using VBA InStr.

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

When working with VBA in Excel, you may have a need to split a string into different parts based on a delimiter.

For example, if you have an address, you can use the VBA Split function to get different parts of the address that are separated by a comma (which would be the delimiter in this case).

SPLIT is an inbuilt string function in Excel VBA that you can use to split a text string based on the delimiter.

Excel VBA SPLIT Function – Syntax

Split ( Expression, [Delimiter], [Limit], [Compare] )
  • Expression: This is the string that you want to split based on the delimiter. For example, in case of the address example, the entire address would be the ‘expression’. In case this is a zero-length string (“”) SPLIT function would return an empty array.
  • Delimiter: This is an optional argument. This is the delimiter that is used to split the ‘Expression’ argument. In case of our address example, a comma is a delimiter that is used to split the address into different parts. If you don’t specify this argument, a space character is considered the default delimiter. In case you give a zero-length string (“”), the entire ‘Expression’ string is returned by the function.
  • Limit: This is an optional argument. Here you specify the total number of substrings that you want to return. For example, if you only want to return the first three substrings from the ‘Expression’ argument, this would be 3. If you don’t specify this argument, the default is -1, which returns all the substrings.
  • Compare: This is an optional argument. Here you specify the type of comparison you want the SPLIT function to perform when evaluating the substrings. The following options are available:
    • When Compare is 0: This is a Binary comparison. This means that if your delimiter is a text string (let’s say ABC), then this would be case-sensitive. ‘ABC’ would not be equal to ‘abc’.
    • When Compare is 1: This is a Text comparison. This means that if your delimiter is a text string (let’s say ABC), then even if you have ‘abc’ in the ‘Expression’ string, it would be considered as a delimiter.

Now that we have covered the basics of the SPLIT function, let’s see a few practical examples.

Example 1 – Split the Words in a Sentence

Suppose I have the text – “The Quick Brown Fox Jumps Over The Lazy Dog”.

I can use the SPLIT function to get each word of this sentence into as a separate item in an array.

The below code would to this:

Sub SplitWords()
Dim TextStrng As String
Dim Result() As String
TextStrng = "The Quick Brown Fox Jumps Over The Lazy Dog"
Result() = Split(TextStrng)
End Sub

While the code does nothing useful, it will help you understand what the Split function in VBA does.

Split function splits the text string and assigns each word to the Result array.

So in this case:

  • Result(0) stores the value “The”
  • Result(1) stores the value “Quick”
  • Result(2) stores the value “Brown” and so on.

In this example, we have only specified the first argument – which is the text to be split. Since no delimiter has been specified, it takes space character as the default delimiter.

Important Note:

  1. VBA SPLIT function returns an array that starts from base 0.
  2. When the result of the SPLIT function is assigned to an array, that array must be declared as a String data type. If you declare it as a Variant data type, it will show a type mismatch error).  In the example above, note that I have declared Result() as a String data type.

Example 2 – Count the Number of Words in a Sentence

You can use the SPLIT function to get the total number of words in a sentence. The trick here is to count the number of elements in the array that you get when you split the text.

The below code would show a message box with the word count:

Sub WordCount()
Dim TextStrng As String
Dim WordCount As Integer
Dim Result() As String
TextStrng = "The Quick Brown Fox Jumps Over The Lazy Dog"
Result = Split(TextStrng)
WordCount = UBound(Result()) + 1
MsgBox "The Word Count is " & WordCount
End Sub

VBA Split Function - Getting the Word Count message

In this case, the UBound function tells us the upper bound of the array (i.e., the maximum number of elements the array has). Since the base of the array is 0, 1 is added to get the total word count.

You can use a similar code to create a custom function in VBA that will take the text as input and return the word count.

The below code will create this function:

Function WordCount(CellRef As Range)
Dim TextStrng As String
Dim Result() As String
Result = Split(WorksheetFunction.Trim(CellRef.Text), " ")
WordCount = UBound(Result()) + 1
End Function

Once created, you can use the WordCount function just like any other regular function.

VBA Split Function - word count formula

This function also handles leading, trailing and double spaces in between words. This has been made possible by using the TRIM function in the VBA code.

In case you want to learn more about how this formula works to count the number of words in a sentence or want to learn about a non-VBA formula way to get the word count, check out this tutorial.

Example 3 – Using a Delimiter Other than Space Character

In the previous two examples, we have only used one argument in the SPLIT function, and the rest were the default arguments.

When you use some other delimiter, you need to specify that in the SPLIT formula.

In the below code, the SPLIT function returns an array based on a comma as the delimiter, and then shows a message with each word in a separate line.

Sub CommaSeparator()
Dim TextStrng As String
Dim Result() As String
Dim DisplayText As String
TextStrng = "The,Quick,Brown,Fox,Jump,Over,The,Lazy,Dog"
Result = Split(TextStrng, ",")
For i = LBound(Result()) To UBound(Result())
DisplayText = DisplayText & Result(i) & vbNewLine
Next i
MsgBox DisplayText
End Sub

VBA Split Function - comma delimiter separate line

In the above code, I have used the For Next loop to go through each element of the ‘Result’ array assign it to the ‘DisplayText’ variable.

Example 4 – Divide an Address into three parts

With the SPLIT function, you can specify how many numbers of splits you want to get. For example, if I don’t specify anything, every instance of the delimiter would be used to split the string.

But if I specify 3 as the limit, then the string will be split into three parts only.

For example, if I have the following address:

2703 Winifred Way, Indianapolis, Indiana, 46204

I can use the Split function in VBA to divide this address into three parts.

VBA Split Function - Specifying number of elements

It splits the first two based on the comma delimiter and remaining part becomes the third element of the array.

The below code would show the address in three different lines in a message box:

Sub CommaSeparator()
Dim TextStrng As String
Dim Result() As String
Dim DisplayText As String
TextStrng = "2703 Winifred Way, Indianapolis, Indiana, 46204"
Result = Split(TextStrng, ",", 3)
For i = LBound(Result()) To UBound(Result())
DisplayText = DisplayText & Result(i) & vbNewLine
Next i
MsgBox DisplayText
End Sub

Resulting Address in separate lines in a message box

One of the practical uses of this could be when you want to divide a single line address into the format shown in the message box. Then you can create a custom function that returns the address divided into three parts (with each part in a new line).

The following code would do this:

Function ThreePartAddress(cellRef As Range)
Dim TextStrng As String
Dim Result() As String
Dim DisplayText As String
Result = Split(cellRef, ",", 3)
For i = LBound(Result()) To UBound(Result())
DisplayText = DisplayText & Trim(Result(i)) & vbNewLine
Next i
ThreePartAddress = Mid(DisplayText, 1, Len(DisplayText) - 1)
End Function

Once you have this code in the module, you can use the function (ThreePartAddress) in the workbook just like any other Excel function.

Split Function in VBA- address in separate lines formula

This function takes one argument – the cell reference that has the address.

Note that for the resulting address to appear in three different lines, you need to apply the wrap text format to the cells (it’s in the Home tab in the Alignment group). If the ‘Wrap Text’ format is not enabled, you’ll see the entire address as one single line.

Example 5 – Get the City Name from the Address

With Split function in VBA, you can specify what part of the resulting array you want to use.

For example, suppose I am splitting the following address based on the comma as the delimiter:

2703 Winifred Way, Indianapolis, Indiana, 46204

The resulting array would look something as shown below:

{"2703 Winifred Way", "Indianapolis", "Indiana", "46204"}

Since this is an array, I can choose to display or return a specific part of this array.

Below is a code for a custom function, where you can specify a number and it will return that element from the array. For example, if I want the state name, I can specify 3 (as it’s the third element in the array).

Function ReturnNthElement(CellRef As Range, ElementNumber As Integer)
Dim Result() As String
Result = Split(CellRef, ",")
ReturnNthElement = Result(ElementNumber - 1)
End Function

The above function takes two arguments, the cell reference that has the address and the element number you want to return. The Split function splits the address elements and assigns it to the Result variable.

Then it returns the element number that you specified as the second argument. Note that since the base is 0, ElementNumber-1 is used to return the correct part of the address.

VBA Split Function - address element by number

This custom formula is best suited when you have a consistent format in all the address – i.e., the city is always mentioned after the two commas. If the data is not consistent, you’ll not get the desired result.

In case you want the city name, you can use 2 as the second argument. In case you use a number that is higher than the total number of elements, it would return the #VALUE! error.

You can further simplify the code as shown below:

Function ReturnNthElement(CellRef As Range, ElementNumber As Integer)
ReturnNthElement = Split(CellRef, ",")(ElementNumber - 1)
End Function

In the above code, instead of using the Result variable, it only returns the specified element number.

So if you have Split(“Good Morning”)(0), it would only return the first element, which is “Good”.

Similarly, in the above code, it only returns the specified element number.

You May Also Like the Following Excel Tutorials:

  • Excel VBA InStr Function – Explained with Examples.
  • How to Sort Data in Excel using VBA (A Step-by-Step Guide).
  • 7 Amazing Things Excel Text to Columns Can Do For You.
  • How to Get the Word Count in Excel.
  • VBA TRIM Function.

In this Article

  • VBA Split Function
    • Using the Split Function with a Delimiter Character
    • Using a Limit Parameter in a Split Function
    • Using the Compare Parameter in a Split Function
    • Using Non-Printable Characters as the Delimiter Character
    • Using the Join Function to Reverse a Split
    • Using the Split Function to do a Word Count
    • Splitting an Address into Worksheet Cells
    • Split String into Worksheet Cells
    • Creating a New Function to Allow Splitting from a Given Point

VBA Split Function

The VBA Split function splits a string of text into substrings based on a specific delimiter character (e.g. a comma, space, or a colon). It is easier to use than writing code to search for the delimiters in the string and then extracting the values.

It could be used if you are reading in a line from a Comma-Separated Value (CSV file) or you have a mailing address that is all on one line, but you want to see it as multiple lines.

The syntax is:

Split expression, delimiter[optional], limit[optional], compare[optional]

The VBA Split function has four parameters:

  • Expression – The string of text that you wish to split into different parts.
  • Delimiter (optional)– string or non-printable character – Defines the delimiter character that is going to be used for the split. If no delimiter character is provided then the default of a space is used.
  • Limit (optional) – number – Defines how many splits will be made. If blank, all available splits will be made within the string. If it is set to 1, then no splits will be made.  Basically, it enables you to separate out a specific number of values starting at the beginning of the string e.g. where the string is very long and you only need the first three splits.
  • Compare (optional) – If your delimiter is a text character then this is used to toggle whether the delimiter is case-sensitive or not. Values are vbBinaryCompare ( case-senstiive) and vbTextCompare (not-case sensitive).

The split function always returns an array.

Simple Example of the Split Function

Sub SplitExample()
'Define variables
Dim MyArray() As String, MyString As String, I As Variant
'Sample string with space delimiters
MyString = "One Two Three Four"
'Use Split function to divide up the component parts of the string
MyArray = Split(MyString)
'iterate through the array created to show each value
For Each I In MyArray
    MsgBox I
Next I
End Sub

In this example, no delimiter is specified because all the words have a space in between them, so the default delimiter (space) can be used.

The array has no dimensions, and is set as a string. The variable I, which is used in the For…Next loop must be dimensioned as a variant.

When this code is run, it will show four message boxes, one for each of the splits e.g. One, Two, Three. Four.

Note that if there is a double space between the words in the string, this will be evaluated as a split, although with nothing in it. This may not be the result that you want to see.

You can fix this problem by using the Replace function to replace any double spaces with a single space:

MyString = Replace(MyString, "  ", " ")

A trailing or leading space can also cause problems by producing an empty split.  These are often very difficult to see. You can remove these extraneous spaces by using the Trim Function:

MyString = Trim(MyString)

Using the Split Function with a Delimiter Character

We can use a delimiter of a semi-colon (;). This is frequently found in email address strings to separate the addresses. You may have an email sent to you which is shared with a number of colleagues and you want to see a list in your worksheet of who it has gone to. You can easily copy the email addresses from the email ‘To’ or ‘Copy’ boxes and into your code.

Sub SplitBySemicolonExample()
'Define variables
Dim MyArray() As String, MyString As String, I As Variant, N As Integer
'Sample string with semi colon delimiters
MyString = "john@myco.com;jane@myco.com;bill@myco.com;james@myco.com"
'Use Split function to divide up the component parts of the string
MyArray = Split(MyString, ";")
'Clear the worksheet
ActiveSheet.UsedRange.Clear
'iterate through the array
For N = 0 To UBound(MyArray)
'Place each email address into the first column of the worksheet
    Range("A" & N + 1).Value = MyArray(N)
Next N
End Sub

Note that a For…Next loop is used to iterate through the array. The first element in the array always starts at zero, and the Upper Bound Function is used to get the maximum number of elements.

After running this code, your worksheet will look like this:

PIC 01

Using a Limit Parameter in a Split Function

The limit parameter allows a specific number of splits to be done from the start of the string.  Unfortunately, you cannot provide a start position or a range of splits to be done, so it is fairly basic. You can build your own VBA code to create a function to do this, and this will be explained later in this article.

Sub SplitWithLimitExample()
'Create variables
Dim MyArray() As String, MyString As String, I As Variant, N As Integer
'Sample string with comma delimiters
MyString = "One,Two,Three,Four,Five,Six"
'Use Split function to divide up the component parts of the string
MyArray = Split(MyString, ",", 4)
'Clear the worksheet
ActiveSheet.UsedRange.Clear
'Iterate through the array
For N = 0 To UBound(MyArray)
    'Place each split into the first column of the worksheet
    Range("A" & N + 1).Value = MyArray(N)
Next N
End Sub

After you run this code, your worksheet will look like this:

PIC 02

Only the first three split values are shown separately. The later three values are shown as one long string and do not get split.

If you choose a limit value that is greater than the number of delimiters within a string, this will not produce an error.  The string will be split into all its component parts as if the limit value had not been provided.

Using the Compare Parameter in a Split Function

The Compare parameter determines if the delimiter is case-sensitive or not. This is not applicable if the delimiters are commas, semi-colons, or colons.

Note: Instead, you can always place Option Compare Text at the top of your module to eliminate case-sensitivity for the entire module.

Sub SplitByCompareExample()
'Create variables
Dim MyArray() As String, MyString As String, I As Variant, N As Integer
'Sample string with X delimiters
MyString = "OneXTwoXThreexFourXFivexSix"
'Use Split function to divide up the component parts of the string
MyArray = Split(MyString, "X", , vbBinaryCompare)
'Clear the worksheet
ActiveSheet.UsedRange.Clear
'iterate through the array
For N = 0 To UBound(MyArray)
    'Place each split into the first column of the worksheet
    Range("A" & N + 1).Value = MyArray(N)
Next N
End Sub

In this example, the string to be split uses the ‘X’ character as a delimiter. However, in this string, there is a mixture of upper and lower case ‘X’ characters. The Compare parameter in the Split function uses an upper case ‘X’ character.

If the Compare parameter is set to vbBinaryCompare, then the lower case ‘x’ characters will be ignored and your worksheet will look like this:

PIC 03

If the Compare parameter is set to vbTextCompare, then the lower case ‘x’ characters will be used in the split and your worksheet will look like this:

PIC 04

Note that the value at cell A6 is truncated because it contains a lower case ‘x’ character. Because the split is not case sensitive, any delimiter which forms part of a sub string will cause a split to happen.

This is an important point to bear in mind when using a text delimiter and vbTextCompare. You can easily end up with the wrong result.

Using Non-Printable Characters as the Delimiter Character

You can use non printable characters as the delimiter, such as a carriage return (a line break).

Here we use the vbCr to specify a carriage return.

Sub SplitByNonPrintableExample()
'Create variables
Dim MyArray() As String, MyString As String, I As Variant, N As Integer
'Sample string with carriage return delimiters
MyString = "One" & vbCr & "Two" & vbCr & "Three" & vbCr & "Four" & vbCr & "Five" & vbCr & "Six"
'Use Split function to divide up the component parts of the string
MyArray = Split(MyString, vbCr, , vbTextCompare)
'Clear the worksheet
ActiveSheet.UsedRange.Clear
'Iterate through the array
For N = 0 To UBound(MyArray)
    'Place each split into the first column of the worksheet
    Range("A" & N + 1).Value = MyArray(N)
Next N
End Sub

In this example, a string is built up using vbCr (carriage return character) as the delimiter.

When this code is run, your worksheet will look like this:

PIC 05

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Using the Join Function to Reverse a Split

The Join function will re-join all the elements of an array, but using a specified delimiter. If no delimiter character is specified then a space will be used.

Sub JoinExample()
'Create variables
Dim MyArray() As String, MyString As String, I As Variant, N As Integer
Dim Target As String
'Sample string with comma delimiters
MyString = "One,Two,Three,Four,Five,Six"
'Place MyString at cell A1
Range("A1").Value = MyString
'Use Split function to divide up the component parts of the string
MyArray = Split(MyString, ",")
'Use Join function to re-create the original string using a semi colon delimiter
Target = Join(MyArray,”;”)
'Place the result string at cell A2
Range("A2").Value = Target
End Sub

This code splits a string with comma delimiters into an array, and joins it back together using semi-colon delimiters.

After running this code your worksheet will look like this:

PIC 06

Cell A1 has the original string with comma delimiters, and cell A2 has the new joined string with semi-colon delimiters.

Using the Split Function to do a Word Count

Bearing in mind that a string variable in Excel VBA can be up to 2Gb long, you can use the split function to do word count in a piece of text.  Obviously, Microsoft Word does it automatically, but this could be useful for a simple text file or text copied from another application.

Sub NumberOfWordsExample()
'Create variables
Dim MyArray() As String, MyString As String
'Sample string with space delimiters
MyString = "One Two Three Four Five Six"
'Remove any double spaces
MyString = Replace(MyString, "  ", " ")
'Remove any leading or trailing spaces
MyString = Trim(MyString)
'Use Split function to divide up the component parts of the string
MyArray = Split(MyString)
'Show number of words using the UBound function
MsgBox "Number of Words " & UBound(MyArray) + 1
End Sub

One of the dangers of this word count code is that it will be thrown by double spaces and leading and trailing spaces.  If these are present, they will be counted as extra words, and the word count will end up as inaccurate.

The code uses the Replace and Trim functions to remove these extra spaces.

The final code line displays the number of words found by using the UBound function to get the maximum element number of the array and then incrementing it by 1. This is because the first array element begins at zero.

Splitting an Address into Worksheet Cells

Mail addresses are often long strings of text with comma delimiters. You may well want to split each part of the address into a separate cell.

Sub AddressExample()
'Create variables
Dim MyArray() As String, MyString As String, N As Integer
'Set up string with Microsoft Corporation Address
MyString = "Microsoft Corporation, One Microsoft Way, Redmond, WA 98052-6399 USA"
'Use the split function to divide the string using a comma delimiter
MyArray = Split(MyString, ",")
'Clear the worksheet
ActiveSheet.UsedRange.Clear
'iterate through the array
For N = 0 To UBound(MyArray)
     'Place each split into the first column of the worksheet
    Range("A" & N + 1).Value = MyArray(N)
Next N
End Sub

Running this code will use the comma delimiter to put each line of the address into a separate cell:

PIC 07

If you only wanted to return the zip code (last array element), then you could use the code:

Sub AddressZipCodeExample()
'Create variables
Dim MyArray() As String, MyString As String, N As Integer, Temp As String
'Set up string with Microsoft Corporation Address
MyString = "Microsoft Corporation, One Microsoft Way, Redmond, WA 98052-6399 USA"
'Use the split function to divide the string using a comma delimiter
MyArray = Split(MyString, ",")
'Clear the worksheet
ActiveSheet.UsedRange.Clear
'Put the Zip Code at cell A1
Range("A1").Value = MyArray(UBound(MyArray))
End Sub

This will only use the last element in the array, which is found by using the UBound function.

On the other hand, you may wish to see all the lines in one cell so that they can be printed onto an address label:

Sub AddressExample()
'Create variables
Dim MyArray() As String, MyString As String, N As Integer, Temp As String
'Set up string with Microsoft Corporation Address
MyString = "Microsoft Corporation, One Microsoft Way, Redmond, WA 98052-6399 USA"
'Use the split function to divide the string using a comma delimiter
MyArray = Split(MyString, ",")
'Clear the worksheet
ActiveSheet.UsedRange.Clear
'iterate through the array
For N = 0 To UBound(MyArray)
     'place each array element plus a line feed character into a string
    Temp = Temp & MyArray(N) & vbLf
Next N
'Put the string onto the worksheet
Range("A1") = Temp
End Sub

This example works the same way as the earlier one, except that it creates a temporary string of all the array elements, but inserting a line feed character after each element.

The worksheet will look like this after the code has been run:

PIC 08

VBA Programming | Code Generator does work for you!

Split String into Worksheet Cells

You can copy the Split array into worksheet cells with just one command:

Sub CopyToRange()
'Create variables
Dim MyArray() As String, MyString As String
'Sample string with space delimiters
MyString = "One,Two,Three,Four,Five,Six"
'Use Split function to divide up the component parts of the string
MyArray = Split(MyString, ",")
'Copy the array into the worksheet
Range("A1:A" & UBound(MyArray) + 1).Value = WorksheetFunction.Transpose(MyArray)
End Sub

When this code has been run, your worksheet will look like this:

PIC 09

Creating a New Function to Allow Splitting from a Given Point

The Limit parameter in the Split function only allows you to specify an upper limit where you want the splitting to stop.  It always commences from the start of the string.

It would be very useful to have a similar function where you can specify the start point of the split within the string, and the number of splits that you want to see from that point onwards. It will also only extract the splits that you have specified into the array, rather than having an enormous string value as the last element in the array.

You can easily build a function (called SplitSlicer) yourself in VBA to do this:

Function SplitSlicer(Target As String, Del As String, Start As Integer, N As Integer)
'Create array variable
Dim MyArray() As String
'Capture the split using the start variable using the delimiter character
MyArray = Split(Target, Del, Start)
‘Check if the start parameter is greater than the number of splits – this can cause problems
If Start > UBound(MyArray) + 1 Then
	‘Display error and exit the function
    MsgBox "Start parameter is greater than number of splits available"
    SplitSlicer = MyArray
    Exit Function
End If
'Put the last array element into the string
Target = MyArray(UBound(MyArray))
    'Split the string using N as the limit
 MyArray = Split(Target, Del, N)
‘Check that the top limit is greater than zero as the code removes the last element
If UBound(MyArray) > 0 Then
'Use ReDim to remove the final element of the array
ReDim Preserve MyArray(UBound(MyArray) - 1)
End If
'Return the new array
SplitSlicer = MyArray
End Function

This function is built with four parameters:

  • Target – string – this is the input string that you want to split
  • Del – string or non-printable character – this is the delimiter character that you use e.g. comma, colon
  • Start – number – this is the start split for your slice
  • N – number – this is the number of splits that you want to do within your slice

None of these parameters are optional or have default values, but you can work that into the code for the function if you wish to extend it further.

The function uses the Split function to create an array using the Start parameter as the Limit.  This means that the array elements will hold the splits up to the start parameter, but the remainder of the string will be the last element, and will not be split.

The last element in the array is transferred back to a string using the UBound function to determine which element this is.

The string is then split again into the array, using N as the limit variable.  This means that splits will be done for the string up to position N, after which the rest of the string will form the last element in the array.

The ReDim statement is used to remove the last element as we only want the specific elements left in the array.  Note that the Preserve parameter is used, otherwise all data in the array will be lost.

The new array is then returned to the code that it was called from.

Note that the code is ‘error proofed’.  Users will often do strange things that you did not consider.  For example, if they try using the function with the Start or N parameter greater than the available number of splits in the string, this is likely to cause the function to fail.

Code is included to check the Start value, and also to make sure that there is an element that can be removed when the ReDim statement is used on the array.

Here is the code to test the function:

Sub TestSplitSlicer()
'Create variables
Dim MyArray() As String, MyString As String
'Define sample string with comma delimiters
MyString = "One,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten"
'Use the Splitslicer function to define new array
MyArray = SplitSlicer(MyString, ",", 4, 3)
'Clear the active sheet
ActiveSheet.UsedRange.Clear
'Copy the array into the worksheet
Range("A1:A" & UBound(MyArray) + 1).Value = WorksheetFunction.Transpose(MyArray)
End Sub

Run this code and your worksheet will look like this:

PIC 10

I’ll add that I had a quick look at Chip Pearson’s answer, and thought it could be improved a little in terms of performance, so I wrote my own which appears to be about 40% faster (feel free to test yourself). It’s faster (1.0E-5 vs 1.7E-5 seconds per cycle) because it uses byte arrays rather than actual characters to compare values. Here’s the function which returns a string array like Chip Pearson’s:

Function SplitMultiDelims2(Text As String, DelimChars As String) As String()
    '''
    'Function to split a string at multiple charachters
    'Use like SplitMultiDelims2("This:is-a,test string", ":-,")
    'Returns an array, in that example SplitMultiDelims2("This:is-a,test string", ":-,")(4) would be "test string"
    '''
    Dim bytes() As Byte
    Dim delims() As Byte
    Dim i As Long, aub As Long, ub As Long
    Dim stack As String
    Dim t() As String
    Dim tLen As Long
    tLen = Len(Text)
    If tLen = 0 Then
        Exit Function
    End If
    ReDim t(1 To tLen)                           'oversize array to avoid Redim Preserve too often
    bytes = StrConv(Text, vbFromUnicode)
    delims = StrConv(DelimChars, vbFromUnicode)
    ub = UBound(bytes)
    For i = 0 To ub
        If Contains(delims, bytes(i)) Then
            aub = aub + 1
            t(aub) = stack
            stack = ""
        Else
            stack = stack & Chr(bytes(i))
        End If
    Next i
    t(aub + 1) = stack
    ReDim Preserve t(1 To aub + 1)               'Works marginally faster if you delete this line,
    'however it returns an oversized array (which is a problem if you use UBOUND of the result,
    'but fine if you are just looking up an indexed value like the 5th string)
    SplitMultiDelims2 = t
End Function

'and a 2nd function called by the first one
Function Contains(arr, v As Byte) As Boolean     'checks if Byte v is contained in Byte array arr
    Dim rv As Boolean, lb As Long, ub As Long, i As Long
    lb = LBound(arr)
    ub = UBound(arr)
    For i = lb To ub
        If arr(i) = v Then
            rv = True
            Exit For
        End If
    Next i
    Contains = rv
End Function

Here’s the test log (his is SplitMultiDelims, mine is SplitMultiDelims2)

> SplitMultiDelims: 1.76105267188204E-05s per cycle 'this is the important figure
> i = 568064 iterations in 10.00390625 seconds
>Test completed: 08/06/2017 10:23:22
> SplitMultiDelims2: 1.05756701906142E-05s per cycle
>i = 947044 iterations in 10.015625 seconds
>Test completed: 08/06/2017 10:23:32
> SplitMultiDelims2: 1.04176859354441E-05s per cycle
>i = 960656 iterations in 10.0078125 seconds
>Test completed: 08/06/2017 10:23:54
> SplitMultiDelims: 1.76228941673255E-05s per cycle
>i = 567887 iterations in 10.0078125 seconds
>Test completed: 08/06/2017 10:24:04

Run in both directions to avoid memory writing handicaps

Test code below uses Timer so not overly precise, but good enough to demonstrate the difference

Sub testSplit()
    Dim t As Double, dt As Double
    Dim s As String
    Dim i As Long
    t = Timer: i = 0: dt = 0: s = ""
    Do Until dt > 10                             'loop for 10 seconds
        s = SplitMultiDelims("This:is-a,test string", ":-,")(1)
        dt = Timer - t
        i = i + 1
    Loop
    Debug.Print "SplitMultiDelims: " & dt / i & "s per cycle" & vbCrLf & "i = " & i; " iterations in " & dt; " seconds" & vbCrLf & "Test completed: " & Now
    t = Timer: i = 0: dt = 0: s = ""
    Do Until dt > 10                             'loop for 10 seconds
        s = SplitMultiDelims2("This:is-a,test string", ":-,")(1)
        dt = Timer - t
        i = i + 1
    Loop
    Debug.Print "SplitMultiDelims2: " & dt / i & "s per cycle" & vbCrLf & "i = " & i; " iterations in " & dt; " seconds" & vbCrLf & "Test completed: " & Now
End Sub

Split is the hardest shot to hit in Bowling. But unlike bowling SPLIT is very simple function to use in excel VBA. Splitting data or string in VBA, sometimes becomes necessary to organize it and to put it in more readable format.

SPLIT-function

SPLIT-function

Here in this article, you will learn about splitting the data/string which is joined with a specific delimiter. Delimiter could be any character or special character. This VBA function basically finds each occurrence of the delimiter and split it and keep storing all the split sub-string in an array. Therefore this VBA function returns a String Array.

Split() Function

This is a VBA function not a Worksheet function (Excel formula). This function returns a one dimensional string array having all the strings split by provided delimiter. If delimiter is not found (even once) then the whole string will be returned by this function.

Syntax:

This is how Syntax will look like as soon as you type VBA.Split in VB Editor
SPLIT - FUNCTION - SYNTAX

Split(<YourString>, <Delimiter>, <Limit>, <CompareMethod>)

Where:

YourString (Mandatory) :

This is the string which has to be split.

Delimiter (Optional) :

Delimiter text by which above text has to be split. For example: Comma (,), Hyphen (-), etc. If this parameter is omitted then Space (” “) is considered as default delimiter.

Limit (Optional) :

This is the maximum number of split in which original text has to be split. The default value is -1 which indicates to show all the split values.

CompareMethod (Optional) :

This is a Numeric value ( 0 or 1) to indicate which method to use for comparison. 0 is for performing a binary comparison. 1 is for performing a textual comparison.

Examples:

With the above theory you may not be more comfortable until you practice with some example by running the VBA code. I have taken few possible cases with different parameters in the below examples. They will make you more comfortable in using this function 🙂

  Example 1 : Omitting all the Optional Parameters

  Example 2 : What is Limit exactly? and How it works?

  Example 3 : What is difference between Binary and Text comparison?

  Special Case in SPLIT Function

Example 1 : Omitting all the Optional Parameters

In the below Example, I have omitted all the optional parameter and passed the String ONLY which has to be split because that is the only parameter which is mandatory in this function.

String : My Name Is Vishwamitra Mishra
Below is the function with my string.
VBA.Split(“My Name Is Vishwamitra Mishra”)
Following is the Array which is returned by the above VBA statement (refer the below picture)
SPLIT - All-Default-Options

Explanation:

In the above code all the optional parameters are omitted. Hence using all the default values for other parameters, this function has returned this array.
Delimiter: As mentioned in theory above, default delimiter is considered as ” ” (space) when omitted hence space is used as delimiter.
Limit:As mentioned above, by default this function split the whole string for all the occurrences of the delimiter found. Hence it has split the whole string with all the delimiter Sapce (” “) found in the string.
CompareMethod :By default it does the text comparison. Hence 1 is passed.
Now in the above string if I use comma (,) as a delimiter instead of Space (” “) then the whole string was returned as a single split because the default delimiter which is space (” “), not found in the main string as shown in the below image:

Split - Default-Parameter

To split the above string you should pass delimiter as comma (,) then it will split the string in to sub-string and put it in an array. In the next example I have used the delimiter as comma (,) to split.

Example 2 : What is difference between Binary and Text comparison?

It is very simple. As the name suggests in binary comparison, system compares the Numeric unicode value of each character. But in Text Comparison, comparison is based on the reference of the current world definition.
For example: Upper case – A and Lower case – a. Both “A” and “a” has different unicode value but as a text both are same.

Refer the below images which shows the difference in both type of comparison.

With Binary Comparison – Same string, Same delimiter and same Limit

Split-Binary-Comparison

With Text Comparison – Same string, Same delimiter and same Limit

Split-Text-Comparison

Important Note:

With the above example difference between Binary Comparison and Text Comparison is clear. Though, rest all the parameters are same in both the statement but still result is different because comparison method is different. Reason is that in Binary Comparison AND is not equal to and but in text comparison they are equal.

Example 3: What is Limit in SPLIT() function exactly ?

Actually limit is the number of split this function has to do of the main string. In other words you can say this is the upper limit of the array which is returned from this function (If it is set other than the default limit which is -1)

Let’s take the below parameters for the VBA.Split function and see how it behaves:
String: My,Name,Is,Vishwamitra,Mishra
Delimiter: comma (,)
Limit: 2
Compare: Default

As I explained above since limit is set as 2 hence Split function will find the first occurrences of the delimiter i.e. comma (,) and put it as first items of the array and rest of the string (though there are occurrences of comma (,)) will be put as 2nd item of the split array. Refer the below picture:

Split-Function-Limit-Explanation

Special Case in SPLIT Function

Split function behaves little different when occurences of delimiter is consecutive in a row or at the start of the string or at the end of the string.
In all the above 3 cases, split function interprets them as they are surrounded by an empty string. Hence in all the above cases an empty string will be sent in the result array. refer the below image as shown:
Split-Special-Case

Explanation:

1. First Array item is shown as an Empty string because of the first occurrence of the delimiter comma (,)
2. Third item of the result array is again and empty string because of 2 consecutive occurrence of the delimiter comma (,)
3. The last item of the result array is again an empty string because of the last occurrence of the delimiter at the end of the string.

Have you got any question or doubt ?

Do comment in this article or mail me. I will try my best to clarify answer your queries as soon as possible.
You can also tweet your query or post your query on my Facebook page for quick response.

What is VBA Split Function in Excel?

The Split function in VBA is a very useful string function that one can use to split strings into multiple substrings based on a delimiter provided to the function and a comparison method. Of course, there are other string functions, too, which convert a string into a substring. But, the Split function can split a string into more than one substring.

In a normal worksheet, the LEFT function, MID functionsThe mid function in Excel is a text function that finds strings and returns them from any mid-part of the spreadsheet. read more, and RIGHT in excelRight function is a text function which gives the number of characters from the end from the string which is from right to left. For example, if we use this function as =RIGHT ( “ANAND”,2) this will give us ND as the result.read more are used as text functionsTEXT function in excel is a string function used to change a given input to the text provided in a specified number format. It is used when we large data sets from multiple users and the formats are different.read more to extract the portion of the sentence. For example, extraction of first, middle, and last names is the common scenario we have seen. But in VBA, we have the more versatile SPLIT function, which will do a similar job for you. SPLIT is a built-in function in Excel VBA that can split the supplied sentence based on the delimiter. So, for example, if you want to split the email address into different parts, the common element in the email address is “@” in all the email IDs, so “@” becomes a delimiter here.

Table of contents
  • What is VBA Split Function in Excel?
    • VBA Split String Function
    • Examples of VBA Split String Function
      • Example #1 – Split the Sentence
      • Example #2 – VBA SPLIT String with UBOUND Function
      • Return Word Count
    • Things to Remember
    • Recommended Articles

VBA Split Function

VBA Split String Function

Like all other functions, split has its syntax. For example, below are the Excel VBA Split string function parameters.

Split Formula

  • Value or Expression: This is nothing but the actual value we were trying to split. For example, if you want to split first and last names, the full name is the value here.
  • [Delimiter]: What is the common element to split the Value or Expression? Email ID’s “@” is the common element, and address comma (,) is the common element. If you ignore this, it considers the space character as the default value.
  • [Limit]: How many substrings do you want from the value or expression you have supplied? For example, if the value is “My name is Excel,” if you supply 3 as the limit, it will show the result in three lines like “My,” “name,” and “is Excel.”
  • [Compare]: Since we do not use the compare argument, skip this optional argument.

In the next sections of the article, we will see how to use the SPLIT function in Excel VBA practically.

Examples of VBA Split String Function

Below are the practical examples of the Split function in Excel VBA.

You can download this VBA Split Function Excel Template here – VBA Split Function Excel Template

Example #1 – Split the Sentence

The Split function returns the result in the array, which will start from 0. All the arrays start from 0, not from 1.

Assume you have the word “My Name is Excel VBA” in cell A1.

VBA Split Example 1

Now, you want to split this sentence into pieces like “My,” “Name,” “is,” “Excel,” and “VBA.” Then, we can return this result using the Excel VBA SPLIT String function.

Step 1: Start the Macro with the name.

VBA Split Example 1-1

Code:

Sub Split_Example1()

End Sub

Step 2: Declare three variables.

VBA Split Example 1-2

Code:

Sub Split_Example1()
  
   Dim MyText As String
   Dim i As Integer
   Dim MyResult() As String

End Sub

Step 3: Now, for the defined variable, My Text assigns the word “My Name is Excel VBA.”

VBA Split Example 1-3

Code:

Sub Split_Example1()
  
  Dim MyText As String
  Dim i As Integer
  Dim MyResult() As String 
  
  MyText = "My Name is Excel VBA"

End Sub

Step 4: Now, apply the VBA Split String function for the “My Result” variable.

VBA Split Example 1-4

Code:

Sub Split_Example1()
  
  Dim MyText As String
  Dim i As Integer
  Dim MyResult() As String
  
  MyText = "My Name is Excel VBA"
  MyResult = Split(

End Sub

Step 5: Expression is our text value. Since we have already assigned our text value to the variable “MyText,” enter this argument here.

VBA Split Example 1-5

Code:

Sub Split_Example1()
  
  Dim MyText As String
  Dim i As Integer
  Dim MyResult() As String
  
  MyText = "My Name is Excel VBA"
  MyResult = Split(MyText)

End Sub

Note: As of now, ignore all the other parameters.

Step 6: Now, “My Result” holds this split result. As we told earlier in the post, the Split function stores the result as an array, so here:

  • My Result (0) = “My”
  • My Result (1) = “Name”
  • My Result (2) = “is”
  • My Result (3) = “Excel”
  • My Result (4) = “VBA”

Even though this code does not impact starting the SPLIT function, we can use this code.

Example #2 – VBA SPLIT String with UBOUND Function

To store the result of the SPLIT function, we can use the vba UBOUND functionUBOUND, also known as Upper Bound, is a VBA function that is used in conjunction with its opposite function, LBOUND, also known as Lower Bound. This function is used to determine the length of an array in a code, and as the name suggests, UBOUND is used to define the array’s upper limit.read more along with the SPLIT function.

The UBOUND function will return the maximum length of the array. In the above example, the maximum length of the array was 5.

Take the same word “My Name is Excel VBA.” Let us split this word and store it from cell A1 onwards.

Step 1: Let us continue from where we left off in the previous example.

VBA Split Example 2

Step 2: Now, apply FOR NEXT LOOP in VBAAll programming languages make use of the VBA For Next loop. After the FOR statement, there is a criterion in this loop, and the code loops until the criteria are reached. read more from 0 to the maximum length of the array, UBOUND.

VBA Split Example 2-1

We started from zero because SPLIT will store the result from zero, not from 1.

Step 3: Now, apply the VBA CELLS propertyCells are cells of the worksheet, and in VBA, when we refer to cells as a range property, we refer to the same cells. In VBA concepts, cells are also the same, no different from normal excel cells.read more and store the result.

Code:

Cells(i + 1, 1).Value = MyResult(i)

Example 2-2

Step 4: Run this code. We would have split values.

Example 2-3

Complete Code:

Sub Split_Example1()
  
  Dim MyText As String
  Dim i As Integer
  Dim MyResult() As String
  
  MyText = "My Name is Excel VBA"
  MyResult = Split(MyText)

  For i = 0 To UBound(MyResult)
      Cells(i + 1, 1).Value = MyResult(i)
  Next i

End Sub

Return Word Count

We can also show the total number of words in the supplied value. Use the below code to show the total number of word counts.

Sub Split_Example2()
  
  Dim MyText As String
  Dim i As Integer
  Dim MyResult() As String
  
  MyText = "My Name is Excel VBA"
  MyResult = Split(MyText)
  
  i = UBound(MyResult()) + 1
  MsgBox "Total Words Count is " & i

End Sub

Return Word Count 1

Please copy and paste the above VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more and run it. The message box will return the result.

Return Word Count 2

Things to Remember

  • The SPLIT function automatically thinks of the delimiter as space if one does not supply the delimiter.
  • To split except space, you must specify the delimiter in double quotes.
  • The SPLIT function stores the result as array results.
  • The UBOUND function returns the maximum length of the array.

Recommended Articles

This article has been a guide to VBA Split Function. Here, we learned how to use Excel’s VBA Split String function, with some practical examples and a downloadable Excel template. Below are useful Excel articles related to VBA: –

  • How to Enable RegEx in VBA?
  • StrComp Function in Excel VBA
  • VBA WorkBook Object
  • VBA Sleep Function in Excel
  • Create a Pivot Table in Excel VBA
  • Do Until Loop in VBA
  • Select Cell in VBA
  • Worksheet Function in VBA
  • Subscript Out of Range

VBA Split Function

VBA Split Function

As the name suggests, a Split is a function that splits strings into different parts. We have many such functions in excel worksheets, such as a left-right and mid function to do so. But when we need any string to differentiate in parts, we use a Split function in VBA. It is one of the best functions in VBA to perform different types of operations on strings.

The split function is basically a substring function that takes a string as an input and gives another string as an output. The only difference between the other substring function like left, right, and mid and split function is that the LEFT, RIGHT & MID function just take one string as an input or argument and returns one string as an output while the SPLIT function returns an array of strings as output.

Formula for Split Function in Excel VBA

VBA Split function has the following syntax:

Syntax of Split

Given below are the arguments for the VBA split function first:

  • Expression as String: This is a mandatory argument in VBA Split function. Expression as string refers to the string we want to break into parts.
  • Delimiter: This is an optional argument. It is the character that is used to break strings into parts. But if we do not provide any delimiter, VBA treats space “ “ as default delimiter.
  • Limit: This is also an optional argument. Limit means the maximum number of parts we want to do of a string. But again, if we do not provide a limit to the function, VBA treats it as default -1, which means the string will break apart each time there is a delimiter in the string.
  • Compare: This final argument is also an optional argument. Compare is a method that is described as one of the two below:
  1. Either it is 0, which means Split will perform a binary comparison which means every character should match itself.
  2. Or it can be 1, which means the Split function will do a textual comparison.

Everything will be clear in a few examples. But let me give a very basic example first of what this function does. Suppose we have an input string as ANAND IS A GOOD BOY. The split string will break it into parts, each word separately. We can also use the Split function to count a number of words in a string, or we can use it to output only a certain amount of words in a given string.

How to Use Excel VBA Split Function?

We will see how to use a VBA Split Excel function with few examples:

You can download this VBA Split Excel Template here – VBA Split Excel Template

VBA Split Function – Example #1

How about we use the above string ANAND IS A GOOD BOY with split function.

Note: In order to use a Split function in VBA, make sure that the developer option is turned on from File Tab from the options section.

Step 1: Go to the Developer tab click on Visual Basic.

Example 1-1

Step 2: A project window appears to click on Sheet 1 to open the code window.

VBA Split Example 1-2

Step 3: When the code window appears, declare a sub-function to start writing the code.

Code:

Sub Sample()

End Sub

VBA Split Example 1-3

Step 4: Declare two variables arrays and one as strings A & B.

Code:

Sub Sample()

Dim A As String
Dim B() As String

End Sub

VBA Split Example 1-4

Step 5: Store the value of the string in A.

Code:

Sub Sample()

Dim A As String
Dim B() As String
A = "ANAND IS A GOOD BOY"

End Sub

VBA Split Example 1-5

Step 6: In the B array, store the value of A using the split function as shown below.

Code:

Sub Sample()

Dim A As String
Dim B() As String
A = "ANAND IS A GOOD BOY"
B = Split(A)

End Sub

VBA Split Example 1-6

Step 7: Use For Loop to break every string.

Code:

Sub Sample()

Dim A As String
Dim B() As String
A = "ANAND IS A GOOD BOY"
B = Split(A)
For i = LBound(B) To UBound(B)
  strg = strg & vbNewLine & "String Number " & i & " - " & B(i)
Next i

End Sub

VBA Split Example 1-7

Step 8: Display it using the Msgbox function.

Code:

Sub Sample()

Dim A As String
Dim B() As String
A = "ANAND IS A GOOD BOY"
B = Split(A)
For i = LBound(B) To UBound(B)
  strg = strg & vbNewLine & "String Number " & i & " - " & B(i)
Next i
MsgBox strg

End Sub

VBA Split Example 1-8

Step 9: Run the code from the run button provided below.

Result of Example 1-9

We get this as output once we run the above code.

VBA Split Function – Example #2

We will now try to take input from a user and split the string into parts.

Step 1: Go to the developer’s tab and click on Visual Basic to open the VB Editor.

Step 2: Click on Sheet 2 from the properties window to open the code window.

Example 2-1

Step 3: In the code window, declare a sub-function to start writing the code.

Code:

Sub Sample1()

End Sub

VBA Split Example 2-2

Step 4: Declare two variables, one as String and one as an Array String.

Code:

Sub Sample1()

Dim A As String
Dim B() As String

End Sub

VBA Split Example 2-3

Step 5: Take the value from the user and store it in the A using the Inputbox function.

Code:

Sub Sample1()

Dim A As String
Dim B() As String
A = InputBox("Enter a String", "Should Have Spaces")

End Sub

VBA Split Example 2-4

Step 6: Store the value of A in Array B using the Split Function.

Code:

Sub Sample1()

Dim A As String
Dim B() As String
A = InputBox("Enter a String", "Should Have Spaces")
B = Split(A)

End Sub

VBA Split Example 2-5

Step 7: Use For Loop to break every string.

Code:

Sub Sample1()

Dim A As String
Dim B() As String
A = InputBox("Enter a String", "Should Have Spaces")
B = Split(A)
For i = LBound(B) To UBound(B)
  strg = strg & vbNewLine & "String Number " & i & " - " & B(i)
Next i

End Sub

VBA Split Example 2-6

Step 8: Display it using the Msgbox function.

Code:

Sub Sample1()

Dim A As String
Dim B() As String
A = InputBox("Enter a String", "Should Have Spaces")
B = Split(A)
For i = LBound(B) To UBound(B)
  strg = strg & vbNewLine & "String Number " & i & " - " & B(i)
Next i
MsgBox strg

End Sub

VBA Split Example 2-7

Step 9: Run the code from the run button. Once we run the code, we get an input message to write a string. Write “I AM A GOOD BOY” as input in the input box and press ok to see the result.

Result of Example 2-8

VBA Split Function – Example #3

We can also use the VBA Split Function to count the number of words in the string. Let us take input from the user and count the number of words in it.

Step 1: Go to the developer’s tab and click on Visual Basic to open VB Editor.

Step 2: Click on Sheet 3 in the project window to open the code window.

Example 3-1

Step 3: Once the code window is open, declare a sub-function to start writing the code.

Code:

Sub Sample2()

End Sub

VBA Split Example 3-2

Step 4: Declare two variables, one as a string and one as an array string.

Code:

Sub Sample2()

Dim A As String
Dim B() As String

End Sub

VBA Split Example 3-3

Step 5: Take input from the user and store it in A using the input box function.

Code:

Sub Sample2()

Dim A As String
Dim B() As String
A = InputBox("Enter a String", "Should Have Spaces")

End Sub

VBA Split Example 3-4

Step 6: Use the Split function and store it in B.

Code:

Sub Sample2()

Dim A As String
Dim B() As String
A = InputBox("Enter a String", "Should Have Spaces")
B = Split(A)

End Sub

VBA Split Example 3-5

Step 7: Use a Msgbox function to display the total number of words.

Code:

Sub Sample2()

Dim A As String
Dim B() As String
A = InputBox("Enter a String", "Should Have Spaces")
B = Split(A)
MsgBox ("Total Words You have entered is : " & UBound(B()) + 1)

End Sub

Example 3-6

Step 8: Run the code from the run button provided. Once we have run the code, it asks for an input for the string. Write “INDIA IS MY COUNTRY” in the box and press ok to see the result.

Result of Example 3-7

Explanation of Excel VBA Split Function

Now we know that the split function in VBA is a substring function that is used to split strings into different parts. The input we take is as a string, while the output displayed is an array.

It is very similar to the other worksheet function, but it is superior as it can break multiple words and return them as an array.

Things to Remember

There are a few things we need to remember about VBA split function:

  • The VBA split function is a substring function.
  • It returns the output as a string.
  • Only the expression is the mandatory argument, while the rest of the arguments are optional.

Recommended Articles

This has been a guide to VBA Split Function. Here we discussed how to use Excel VBA Split Function along with practical examples and a downloadable excel template. You can also go through our other suggested articles to learn more –

  1. VBA While Loop
  2. VBA CDEC
  3. VBA Do While Loop
  4. VBA LBound

Like this post? Please share to your friends:
  • Delicious meaning of the word
  • Delphi excel createoleobject excel application
  • Deleting words in excel
  • Delphi excel borders linestyle
  • Deleting spaces in word