Saturday, July 23, 2016

How to use the SPLIT Function (VBA)

Description

The Microsoft Excel SPLIT function will split a string into substrings based on a delimiter. The result is returned as an array of substrings.

Syntax

The syntax for the SPLIT function in Microsoft Excel is:
Split ( expression [,delimiter] [,limit] [,compare] )

Parameters or Arguments

expression
The string to split into substrings based on a delimiter.
delimiter
Optional. The delimiter used to split expression into substrings. If not specified, the delimiter will default to a space character.
limit
Optional. The maximum number of substrings split from expression. If not specified, the limit will default to -1 which will split out all substrings.
compare
Optional. This is the type of comparison to perform when parsing the substrings and can be one of the following:
VBA ConstantValueExplanation
CompareMethod.Binary0Binary comparison
CompareMethod.Text1Textual comparison

Applies To

  • Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Type of Function

  • VBA function (VBA)

Example (as VBA Function)

The SPLIT function can only be used in VBA code in Microsoft Excel.
Let's look at some Excel SPLIT function examples and explore how to use the SPLIT function in Excel VBA code:
Split("Tech on the Net")
Result: {"Tech", "on", "the", "Net"}

Split("172.23.56.4", ".")
Result: {"172", "23", "56", "4"}

Split("A;B;C;D", ";")
Result: {"A", "B", "C", "D"}

Split("A;B;C;D", ";", 1)
Result: {"A;B;C;D"}

Split("A;B;C;D", ";", 2)
Result: {"A", "B;C;D"}

Split("A;B;C;D", ";", 3)
Result: {"A", "B", "C;D"}

Split("A;B;C;D", ";", 4)
Result: {"A", "B", "C", "D"}
For example:
Dim LString As String
Dim LArray() As String

LString = "TechOnTheNet.com"
LArray = Split(LString, ".")

MsgBox LArray(0)
MsgBox LArray(1)
In this example, the variable called LArray would now contain the array {"TechOnTheNet", "com"}. The two MsgBox statements would display the value stored in each element of the array.