Excel vba string array to string

Содержание

  1. Преобразование массива в строку
  2. Преобразование строки в массив
  3. Split function
  4. Syntax
  5. Settings
  6. Example
  7. See also
  8. Support and feedback
  9. Функция Split
  10. Синтаксис
  11. Параметры
  12. Пример
  13. См. также
  14. Поддержка и обратная связь
  15. VBA String Array
  16. Excel VBA String Array
  17. Examples of String Array in Excel VBA
  18. Example #1
  19. Example #2
  20. Example #3
  21. Things to Remember
  22. Recommended Articles
  23. Convert Variable Array to String
  24. 4 Answers 4

Преобразование массива в строку

Преобразовать массив в строку позволяет функция Join() . Элементы массива должны быть строками или значениями типа Variant , которые автоматически преобразуются в строку. Попытка передать в функцию, например, массив со значениями типа Integer приведет к ошибке. Формат функции:

Если параметр не указан, то в качестве разделителя используется пробел. Пример:

Преобразование строки в массив

Функция Split( [, [, [, ]]]) разделяет строку на подстроки по указанному разделителю и добавляет их в массив. Если в параметре указана пустая строка, то функция возвращает пустой массив. Если параметр не указан, то в качестве разделителя используется символ пробела. Если в параметре задано число, то в массиве будет указанное количество подстрок. Если подстрок больше указанного количества, то последний элемент массива будет содержать остаток строки. По умолчанию параметр имеет значение -1 , которое означает, что лимит не установлен. Пример:

Если разделитель не найден в строке, то массив будет состоять из одного элемента, представляющего исходную строку:

Параметр задает способ сравнения. Можно указать следующие константы или соответствующие им значения:

  • vbBinaryCompare — 0 — двоичное сравнение. Сравнение зависит от регистра символов;
  • vbTextCompare — 1 — текстовое сравнение. Регистр символов при сравнении не учитывается.

Если параметр не указан, то по умолчанию сравнение зависит от значения инструкции Option Compare , которая должна быть расположена в самом начале модуля. Если инструкция имеет значение Binary (или инструкция не указана), то используется двоичное сравнение, а если Text — то текстовое сравнение. Пример:

Статьи по Visual Basic for Applications (VBA)

Помощь сайту

ПАО Сбербанк:
Счет: 40817810855006152256
Реквизиты банка:
Наименование: СЕВЕРО-ЗАПАДНЫЙ БАНК ПАО СБЕРБАНК
Корреспондентский счет: 30101810500000000653
БИК: 044030653
КПП: 784243001
ОКПО: 09171401
ОКОНХ: 96130
Скриншот реквизитов

Источник

Split function

Returns a zero-based, one-dimensional array containing a specified number of substrings.

Syntax

Split(expression, [ delimiter, [ limit, [ compare ]]])

The Split function syntax has these named arguments:

Part Description
expression Required. String expression containing substrings and delimiters. If expression is a zero-length string(«»), Split returns an empty array, that is, an array with no elements and no data.
delimiter Optional. String character used to identify substring limits. If omitted, the space character (» «) is assumed to be the delimiter. If delimiter is a zero-length string, a single-element array containing the entire expression string is returned.
limit Optional. Number of substrings to be returned; -1 indicates that all substrings are returned.
compare Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings section for values.

Settings

The compare argument can have the following values:

Constant Value Description
vbUseCompareOption -1 Performs a comparison by using the setting of the Option Compare statement.
vbBinaryCompare 0 Performs a binary comparison.
vbTextCompare 1 Performs a textual comparison.
vbDatabaseCompare 2 Microsoft Access only. Performs a comparison based on information in your database.

Example

This example shows how to use the Split function.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Функция Split

Возвращает одномерный массив с основанием 0, содержащий указанное число подстрок.

Синтаксис

Split(expression, [ разделитель, [ limit, [ compare ]]])

Синтаксис функции Split включает следующие именованные аргументы:

Part Описание
выражение Обязательно. Строковое выражение, содержащее подстроки и разделители. Если аргумент expression является строкой нулевой длины («»), функция Split возвращает пустой массив — без элементов и данных.
Разделитель Необязательный параметр. Строковый символ, используемый для разделения подстрок. Если этот аргумент не указан, в качестве разделителя используется знак пробела (» «). Если аргумент delimiter является строкой нулевой длины, возвращается массив с одним элементом, содержащим всю строку из аргумента expression.
Предел Необязательный параметр. Количество возвращаемых подстрок; -1 указывает, что возвращаются все подстроки.
compare Необязательно. Числовое значение, указывающее тип сравнения, который будет использоваться при оценке подстрок. Значения см. в разделе «Параметры».

Параметры

Аргумент compare может принимать следующие значения:

Константа Значение Описание
vbUseCompareOption –1 Выполняет сравнение, используя параметр оператора Option Compare.
vbBinaryCompare 0 Выполняется двоичное сравнение.
vbTextCompare 1 Выполняется текстовое сравнение.
vbDatabaseCompare 2 Только Microsoft Access. Выполняется сравнение на основе сведений из базы данных.

Пример

В этом примере показано, как использовать функцию Split .

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA String Array

Excel VBA String Array

In VBA, a String Array is nothing but an array variable that can hold more than one string value with a single variable.

Table of contents

Code:

In the above code, we have declared an array variable and assigned the length of an array as 1 to 5.

Next, we have written a code to show these city names in the message box.

Next, we have written a code to show these city names in the message box.

When we run this code, we will get a message box that shows all the city names in a single message box.

We all know this has saved much time from our schedule by eliminating the task of declaring individual variables for each city. However, one more thing you need to learn is we can still reduce the code of lines we write for string values. So, let’s look at how we write code for VBA string Code For VBA String String functions in VBA do not replace the string; instead, this function creates a new string. There are numerous string functions in VBA, all of which are classified as string or text functions. read more arrays.

Examples of String Array in Excel VBA

Below are examples of an Excel VBA string array.

Example #1

As we have seen in the above code, we learned we could store more than one value in the variable based on the array size.

We do not need to decide the array length well in advance.

Code:

Inside the array, pass the values on double quotes, each separated by a comma (,).

Code:

Code:

One change we have made in the above code is that we have not decided on the lower limit and upper limit of an array variable. Therefore, the ARRAY function array count will start from 0, not 1.

So, that is the reason we have mentioned the values as CityList(0), ClityList(1), CityList(2), CityList(3), and CityList(4).

Example #2

VBA String Array with LBOUND & UBOUND Functions

If you don’t want to show all the city lists in a single message box, then you need to include loops and define one more variable for loops.

Now, to include FOR NEXT loop, we are unsure how many times we need to run the code. Of course, we can decide five times in this case, but that is not the right way to approach the problem. So, how about the idea of auto lower and higher level array length identifiers?

When we open FOR NEXT loop, we usually decide the loop length as 1 to 5 or 1 to 10, depending upon the situation. So, instead of manually entering the numbers, let’s automatically use the LBOUND and UBOUND functions to decide on the lower and upper values.

Now, show the value in the message box. Instead of inserting the serial number, let the loop variable “k” take the array value automatically.

Code:

Now, the message box will show each city name separately.

Example #3

VBA String Array with Split Function

Now, assume you have city names like the one below.

Bangalore;Mumbai;Kolkata;Hydrabad;Orissa

In this case, all the cities combine with the colon separating each city. Therefore, we need to use the SPLIT function to separate each city in such cases.

For Expression, supply the city list.

Code:

The next argument is “Delimiter,” which is the one character separating each city from other cities. In this case, “Colon.”

Code:

Now, the SPLIT function split values determine the highest array length.

Things to Remember

  • The LBOUND and UBOUND are functions to determine the array lengths.
  • The ARRAY function can hold many values for a declared variable.
  • Once we want to use the ARRAY function, do not decide the array length.

Recommended Articles

This article is a guide to VBA String Array. Here, we discuss how to declare the VBA string array variable, which can hold more than one string value, along with practical examples and a downloadable template. Below you can find some useful Excel VBA articles: –

Источник

Convert Variable Array to String

I am trying to convert a variable array to a string using vba. I have tried 2 methods but non of them work, they both seem to bloc on at the same point.

They both error on the MsgBox line. What do I do wrong ?

4 Answers 4

The value you are trying to join is not an array of strings. Join is supposed to be used on arrays

Their example is:

You code should look something like:

Tranpose can be used to produce a 1D array or strings for an individual column or row.

So for A1:A10 you could used just

to work on a row you need a second Transpose , so for A1:K1

It looks like you think your val and CodeRange variables are Arrays, when in fact they are not. You have declared them as Variants , but not Variant Arrays , which I suspect is you goal. Add brackets to declare a variable as an Array: Dim CodeRange() as Variant

As @Brandon Keck says, Join is expecting an Array.

I appologize for the first rendition of this post, I just pasted the Function directly from Excel’s VBA project window. I did not realize that the formatting would be lost. I also wasn’t aware that I could create code fences with backticks ` or tildes

I modified the Function to include the table Field name(s) and the contents of the Criteria1 Array when the type is «.Operator = xlFilterValues». Now instead of getting:

I get [Surname:=Gedye,=Sole,=Williams] AND [Active:=1]

Источник

The Excel VBA Join function returns a single string from an array of strings separated by a delimiter.

This is the opposite of the VBA Split function which splits a string into a VBA Array across a delimiter.

VBA Join Function Syntax

Join( sourcearray [, delimiter ] )

Parameters

sourcearray
The one dimensional string array which elements you want to join into a single string.

delimiter
Optional. A delimiter that is to separate the joined string items in the array. By default this is a Space character.

Examples using the VBA Join functions

Simple concatenated string from Array

Dim arr As Variant, joinString as String

joinString = Join(Array("Dragon", "Dog", "DRAGONfly", "Cat", "fly"))

Debug.Print joinString 'Result: "Dragon Dog DRAGONfly Cat fly"

Notice that all items are separated in the final string. This is because the default delimiter is a Space character.

In above example I also used the VBA Array function to quickly define a VBA Array of strings.

Below a simple example showing that only String arrays can be Joined:

Dim arr As Variant, joinString as String

joinString = Join(Array(1, 2, 3 )) 'ERROR: array is not a String array

joinString = Join(Array("1", "2", "3" )) 'OK. Result: "1 2 3"

Concatenated string using delimiter

We will modify code example above using a delimiter of our choosing:

Dim arr As Variant, joinString as String

joinString = Join(Array("Dragon", "Dog", "DRAGONfly", "Cat", "fly"), ";")

Debug.Print joinString 'Result: "Dragon;Dog;DRAGONfly;Cat;fly"

In VBA, a String Array is nothing but an array variable that can hold more than one string value with a single variable.

For example, look at the 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 below.

Table of contents
  • Excel VBA String Array
    • Examples of String Array in Excel VBA
      • Example #1
      • Example #2
      • Example #3
    • Things to Remember
    • Recommended Articles

Code:

Sub String_Array_Example()

Dim CityList(1 To 5) As Variant

CityList(1) = "Bangalore"
CityList(2) = "Mumbai"
CityList(3) = "Kolkata"
CityList(4) = "Hyderabad"
CityList(5) = "Orissa"

MsgBox CityList(1) & ", " & CityList(2) & ", " & CityList(3) & ", " & CityList(4) & ", " & CityList(5)

End Sub

In the above code, we have declared an array variable and assigned the length of an array as 1 to 5.

Dim CityList(1 To 5) As Variant

Next, we have written a code to show these city names in the message box.

CityList(1) = "Bangalore"

CityList(2) = "Mumbai"

CityList(3) = "Kolkata"

CityList(4) = "Hyderabad"

CityList(5) = "Orissa"

Next, we have written a code to show these city names in the message box.

MsgBox CityList(1) & ", " & CityList(2) & ", " & CityList(3) & ", " & CityList(4) & ", " & CityList(5)

When we run this code, we will get a message box that shows all the city names in a single message box.

VBA String Array Example 1-1

We all know this has saved much time from our schedule by eliminating the task of declaring individual variables for each city. However, one more thing you need to learn is we can still reduce the code of lines we write for string values. So, let’s look at how we write code for VBA stringString functions in VBA do not replace the string; instead, this function creates a new string. There are numerous string functions in VBA, all of which are classified as string or text functions.read more arrays.

Examples of String Array in Excel VBA

Below are examples of an Excel VBA string array.

You can download this VBA String Array Excel Template here – VBA String Array Excel Template

Example #1

As we have seen in the above code, we learned we could store more than one value in the variable based on the array size.

We do not need to decide the array length well in advance.

Code:

Sub String_Array_Example1()

Dim CityList() As Variant

End Sub

VBA String Array Example 1-1

As you can see above, we have not written any lengths in the parenthesis. So now, for this variable, let’s insert values using VBA ARRAY functionArrays are used in VBA to define groups of objects. There are nine different array functions in VBA: ARRAY, ERASE, FILTER, ISARRAY, JOIN, LBOUND, REDIM, SPLIT, and UBOUND.read more.

VBA String Array Example 1-2.png

Inside the array, pass the values on double quotes, each separated by a comma (,).

Code:

Sub String_Array_Example()

Dim CityList() As Variant

CityList = Array("Bangalore", "Mumbai", "Kolkata", "Hyderabad", "Orissa")

End Sub

VBA String Array Example 1-3.png

Now, retain the old code to show the result of city names in the message box in VBAVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.

Code:

Sub String_Array_Example1()

Dim CityList() As Variant

CityList = Array("Bangalore", "Mumbai", "Kolkata", "Hyderabad", "Orissa")

MsgBox CityList(0) & ", " & CityList(1) & ", " & CityList(2) & ", " & CityList(3) & ", " & CityList(4)

End Sub

One change we have made in the above code is that we have not decided on the lower limit and upper limit of an array variable. Therefore, the ARRAY function array count will start from 0, not 1.

So, that is the reason we have mentioned the values as  CityList(0), ClityList(1), CityList(2), CityList(3), and CityList(4).

Now, run the code through excel shortcut keyAn Excel shortcut is a technique of performing a manual task in a quicker way.read more F5 or manually. Again, we get the same result as the previous code.

VBA String Array Example 1.gif

Example #2

VBA String Array with LBOUND & UBOUND Functions

If you don’t want to show all the city lists in a single message box, then you need to include loops and define one more variable for loops.

VBA String Array Example 1-6

Now, to include FOR NEXT loop, we are unsure how many times we need to run the code. Of course, we can decide five times in this case, but that is not the right way to approach the problem. So, how about the idea of auto lower and higher level array length identifiers?

When we open FOR NEXT loop, we usually decide the loop length as 1 to 5 or 1 to 10, depending upon the situation. So, instead of manually entering the numbers, let’s automatically use the LBOUND and UBOUND functions to decide on the lower and upper values.

VBA String Array Example 1-7

For LBound and Ubound, we have supplied an array name, CityList. The VBA LBoundLBound in VBA or “Lower Bound” extracts the lowest number of an array. For example, if the array says “Dim ArrayCount (2 to 10) as String” then using LBound function we can find the least number of the array length i.e. 2.read more identifies the array variable’s lower value. 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 identifies the upper value of the array variable.

Now, show the value in the message box. Instead of inserting the serial number, let the loop variable “k” take the array value automatically.

Code:

Sub String_Array_Example1()

Dim CityList() As Variant

Dim k As Integer

CityList = Array("Bangalore", "Mumbai", "Kolkata", "Hyderabad", "Orissa")

For k = LBound(CityList) To UBound(CityList)

MsgBox CityList(k)

Next k

End Sub

LBound & UBound Example 1-8

Now, the message box will show each city name separately.

VBA String Array Example 1.gif

Example #3

VBA String Array with Split Function

Now, assume you have city names like the one below.

Bangalore;Mumbai;Kolkata;Hydrabad;Orissa

In this case, all the cities combine with the colon separating each city. Therefore, we need to use the SPLIT function to separate each city in such cases.

Split Example 2

For Expression, supply the city list.

Code:

Sub String_Array_Example2()

Dim CityList() As String

Dim k As Integer

CityList = Split("Bangalore;Mumbai;Kolkata;Hydrabad;Orissa",

For k = LBound(CityList) To UBound(CityList)
MsgBox CityList(k)
Next k

End Sub

Split Example 2-1

The next argument is “Delimiter,” which is the one character separating each city from other cities. In this case, “Colon.”

Code:

Sub String_Array_Example2()

Dim CityList() As String

Dim k As Integer

CityList = Split("Bangalore;Mumbai;Kolkata;Hydrabad;Orissa", ";")

For k = LBound(CityList) To UBound(CityList)
MsgBox CityList(k)
Next k

End Sub

split Example 2-2.png

Now, the SPLIT function split values determine the highest array length.

Things to Remember

  • The LBOUND and UBOUND are functions to determine the array lengths.
  • The ARRAY function can hold many values for a declared variable.
  • Once we want to use the ARRAY function, do not decide the array length.

Recommended Articles

This article is a guide to VBA String Array. Here, we discuss how to declare the VBA string array variable, which can hold more than one string value, along with practical examples and a downloadable template. Below you can find some useful Excel VBA articles: –

  • VBA String Comparison
  • Find Array Size in VBA
  • SubString in Excel VBA
  • Variant Data Type in VBA

To simplify the conversion of a variant array to a string array in Microsoft Excel we have made a set of utility functions. The method will also flatten any variant arrays within the source array (i.e. jagged arrays).

' Array Variant to String
Public Function VariantArrayToStringArray(ByVal arrVariants As Variant) As String()
    Dim arrStrings() As String
   
    ' Get the string array
    Call ParamArrayToStringArray(arrVariants, arrStrings)
   
    ' Get the string array
    VariantArrayToStringArray = arrStrings
End Function

' Array Variant to String
Public Sub ParamArrayToStringArray(ByVal arrVariants As Variant, ByRef arrStrings() As String)
    Dim intLength As Integer
   
    ' Handle the array
    Call ParamArrayToStringArrayInternal(arrVariants, arrStrings, intLength)
End Sub


' Array Variant to String
Private Sub ParamArrayToStringArrayInternal(ByVal arrVariants As Variant, ByRef arrStrings() As String, ByRef intLength As Integer)
    ' Parameter is array?
    If (IsArray(arrVariants)) Then
        Dim i As Integer
        Dim objValue As Variant
   
        ' Walk through the specified partner objects
        For i = LBound(arrVariants) To UBound(arrVariants) Step 1
            ' Get the value
            objValue = arrVariants(i)
       
            ' Array to string
            Call ParamArrayToStringArrayInternal(objValue, arrStrings, intLength)
        Next
    Else
        ' Next item
        intLength = intLength + 1
   
        ' Expand array
        ReDim Preserve arrStrings(1 To intLength)

        ' Set the value
        arrStrings(intLength) = CStr(arrVariants)
    End If
End Sub

' String Array
' Convert ParamArray to String array
Public Function StringArray(ParamArray arrValues() As Variant) As String()
    ' Get the string array
    StringArray = VariantArrayToStringArray(arrValues)
End Function

Usage

Here is an example on how to use the method called VariantArrayToStringArray:

' Source array
Dim arrVariants() As Variant

' Set the array length
ReDim arrVariants(1 To 4)

' Set the array values
arrVariants(1) = 1          ' Integer
arrVariants(2) = 2.2        ' Single
arrVariants(3) = "Text"     ' Text
arrVariants(4) = True       ' Boolean
    
' Destination array
Dim arrStrings() As String

' Convert variant array to string array
arrStrings = VariantArrayToStringArray(arrVariants)

The method will return an array with the following string values:
arrStrings(1) = “1”
arrStrings(2) = “2.2”
arrStrings(3) = “Text”
arrStrings(4) = “True”


Here is an example on how to use the function StringArray to create a string array from a ParamArray of variants. It is a fast way to initialize an array of strings.

' Destination array
Dim arrStrings() as String

' Get string array
arrStrings = StringArray("This", "is", "a", "test")

The array arrStrings now contains the following values:

arrStrings(0) = “This”
arrStrings(1) = “is”
arrStrings(2) = “a”
arrStrings(3) = “test”

Regional settings

Please notice that the decimal separator for singles/floats/doubles is dependent on your computer’s regional settings. In some regions the decimal separator is a comma. For item 2 the result value is “2.2” in the USA, while in the Scandinavian countries the result value is “2,2”.

To always use the dot as a decimal separator, replace the expression CStr(arrVariants) with Trim(Str(arrVariants)). In some cases I have experienced that the Str function adds a space to the result string. This space can be removed by Trim. The Str function does unfortunately not support a string as an input value, so we need to do an additional check.

' Contains decimal numbers?
If (VarType(arrVariants) <> vbString) Then
     arrStrings(intLength) = Trim(Str(arrVariants))
Else
    ' Convert String to String
    arrStrings(intLength) = CStr(arrVariants)
End If

The full source code for the modified method ParamArrayToStringArrayInternal is shown below.

' Array Variant to String
Private Sub ParamArrayToStringArrayInternal(ByVal arrVariants As Variant, ByRef arrStrings() As String, ByRef intLength As Integer)
    ' Parameter is array?
    If (IsArray(arrVariants)) Then
        Dim i As Integer
        Dim objValue As Variant
   
        ' Walk through the specified partner objects
        For i = LBound(arrVariants) To UBound(arrVariants) Step 1
            ' Get the value
            objValue = arrVariants(i)
       
            ' Array to string
            Call ParamArrayToStringArrayInternal(objValue, arrStrings, intLength)
        Next
    Else
        ' Next item
        intLength = intLength + 1
   
        ' Expand array
        ReDim Preserve arrStrings(1 To intLength)

        ' Contains decimal numbers?
        If (VarType(arrVariants) <> vbString) Then
            arrStrings(intLength) = Trim(Str(arrVariants))
        Else
            ' Convert String to String
            arrStrings(intLength) = CStr(arrVariants)
        End If
    End If
End Sub

Simplified variant

One of our readers, Pete, proposed a simpler version of the above function (see the comments field below). This variant, however, does not handle jagged arrays, i.e. arrays inside arrays. The function is included for your reference:

' Converts Var array to a string array
Public Function Variant2String(ByRef vArr() As Variant) As String()
    Dim i As Long
    Dim sArr() As String
    ReDim sArr(LBound(vArr) To UBound(vArr)) As String

    For i = LBound(vArr) To UBound(vArr) Step 1
        sArr(i) = CStr(vArr(i))
    Next

    Variant2String = sArr
End Function

Compilation

It is recommended to add the expression Option Explicit at the beginning of your source file to ensure that the code is compiled correctly.

Related

  • Format String in Excel VBA
  • Get Microsoft Excel

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.)

Понравилась статья? Поделить с друзьями:
  • Excel vba stop vba
  • Excel vba stop for
  • Excel vba sql not in
  • Excel vba split несколько разделителей
  • Excel vba split for