Vba excel строка как массив

 

Alex.Karev

Пользователь

Сообщений: 7
Регистрация: 24.03.2013

Всем доброго дня!
Прошу уважаемых форумчан помочь советом по следующей ситуации.

[VBA]: обрабатывается построчно текстовый файл большого размера (100+ Мб).
Каждая считанная строка имеет следующий вид (пример):

Код
{{"Василий","Инженер",55000,35},{"Михаил","Юрист",65000,42},{"Светлана","офис-менеджер",35000,27}}

Согласно синтаксису VB (не VBA), подобная запись информации (с использованием вложенных литералов `{` и `}` ) соответствует записи двумерного массива.

А синтаксис описания массивов в VBA, к сожалению, иной и фигурные скобки не воспринимаются.

Требуется: присвоить содержимое вышеуказанной строки переменной, являющей двумерным массивом для последующей обработки строк и столбцов. К примеру — суммированию в цикле зарплат сотрудников, чей возраст менее 40 лет.

Проблема: описание массивов в VBA не воспринимает фигурные скобки. Можно было бы через RegExp привести строку к виду

Код
Array(Array("Василий","Инженер",55000,35),Array("Михаил","Юрист",65000,42),Array("Светлана","Офис-менеджер",35000,27))

и применить (бы) evaluate, но Evaluate в VBA обрабатывает только арифметические выражения…

Я пытался воспользоваться другим редактором:

Код
Dim d As New MSScriptControl.ScriptControl
d.Language = "VBScript"...

но он так же отличается от VB и не воспринимает синтаксис массива с применением фигурных скобок.

Уважаемые коллеги, подскажите, какие есть идеи или варианты на Ваш взгляд, кроме простого перебора строки и заполнения в цикле двумерного массива для приведения его к виду

Цитата
Василий      Инженер         55000    35
Михаил       Юрист           65000    42
Светлана     Офис-менеджер   35000    27

Скорость работы решения важна, поскольку файл — большого размера.

Заранее благодарю Вас за участие в обсуждении!

Изменено: Alex.Karev18.08.2016 10:39:52

A string is a collection of characters joined together. When these characters are divided and stored in a variable, that variable becomes an array for these characters. The method we use to split a string into an array is by using the SPLIT function in VBA, which splits the string into a one-dimensional string.

Like worksheets in VBA, too, we have functions to deal with String or Text values. We are familiar with the string operations like extracting the first name, last name, middle name, etc. But how about the idea of splitting string values into arrays in VBA? Yes, you heard it correctly we can split string sentences into an array using VBA codingVBA 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. This special article will show you how to split the string into an array in Excel VBA.

Table of contents
  • Excel VBA Split String into Array
    • What is Split String into an Array?
    • How to Convert Split String into an Array in Excel VBA?
      • Example #1
      • Example #2
    • Things to Remember
    • Recommended Articles

VBA-Split-String-into-Array

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Split String into Array (wallstreetmojo.com)

What is Split String into an Array?

Let me clarify this first, “String into Array” is nothing but “different parts of the sentence or string will split into multiple parts.” So, for example, if the sentence is “Bangalore is the capital city of Karnataka,” each word is a different array.

So, how to split this sentence into an array is the topic of this article.

How to Convert Split String into an Array in Excel VBA?

To convert the split string into an array in VBA, we have a function called “SPLIT.” This VBA functionVBA functions serve the primary purpose to carry out specific calculations and to return a value. Therefore, in VBA, we use syntax to specify the parameters and data type while defining the function. Such functions are called user-defined functions.read more splits supplied string values into different parts based on the delimiter provided.

For example, if the sentence is “Bangalore is the capital city of Karnataka,” space is the delimiter between each word.

Below is the syntax of the SPLIT function.

Split Function

  • Value or Expression: This is the string or text value we try to convert to the array by segregating each part of the string.
  • [Delimiter]: This is nothing but the common things which separate each word in the string. In our sentence, “Bangalore is the capital city of Karnataka,” each word is separated by a space character, so our delimiter is space here.
  • [Limit]: Limit is nothing but how many parts we want as a result. For example, in the sentence “Bangalore is the capital city of Karnataka,” we have seven parts. If we need only three parts, then we will get the first part as “Bangalore,” the second part as “is,” and the third part as the rest of the sentence, i.e., “the capital city of Karnataka.”
  • [Compare]: One does not use this99% of the time, so let us not touch this.

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

Example #1

Now, let us see practical examples.

Step 1: Define the VBA variableVariable declaration is necessary in VBA to define a variable for a specific data type so that it can hold values; any variable that is not defined in VBA cannot hold values.read more to hold the string value.

Code:

Sub String_To_Array()

  Dim StringValue As String

End Sub

VBA Split String into Array - Example 1

Step 2: For this variable, assign the string “Bangalore is the capital city of Karnataka.”

Code:

Sub String_To_Array()

 Dim StringValue As String
 StringValue = "Bangalore is the capital city of Karnatka"

End Sub

VBA Split String into Array - Example 1-1

Step 3: Next, define one more variable which can hold each part of the above string value. We need to remember this because the sentence has more than one word, so we need to define the variable as “Array” to hold more than one value.

In this case, we have 7 words in the string so define the array as follows.

Code:

Sub String_To_Array()

 Dim StringValue As String
 StringValue = "Bangalore is the capital city of Karnatka"

 Dim SingleValue() As String

End Sub

VBA Split String into Array - Example 1-2

Now, for this array variable, we will use the SPLIT function to split the string into an array in Excel VBAArrays 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.

Code:

Sub String_To_Array()

 Dim StringValue As String
 StringValue = "Bangalore is the capital city of Karnataka"

 Dim SingleValue() As String
 SingleValue = Split(StringValue, " ")

End Sub

VBA Split String into Array - Example 1-3

The expression is our string value, i.e., the variable already holds the string value, so enter the variable name only.

VBA Split String into Array - Example 1-4

The delimiter in this string is a space character so supply the same.

Code:

Sub String_To_Array()

 Dim StringValue As String
 StringValue = "Bangalore is the capital city of Karnataka"

 Dim SingleValue() As String
 SingleValue = Split(StringValue, " ")

End Sub

As of now, leave other parts of the SPLIT function.

The SPLIT function splits the string value into 7 pieces, each word segregated at the expense of space character. Since we have declared the variable “SingleValue” as an array, we can assign all 7 values to this variable.

We can write the code as follows.

Code:

Sub String_To_Array()

 Dim StringValue As String
 StringValue = "Bangalore is the capital city of Karnataka"

 Dim SingleValue() As String
 SingleValue = Split(StringValue, " ")

 MsgBox SingleValue(0)

End Sub

Run the code and see what we get in the message box.

Example 1-5

Now, we can see the first word, “Bangalore.” To show other words, we can write the code as follows.

Code:

Sub String_To_Array()

 Dim StringValue As String
 StringValue = "Bangalore is the capital city of Karnataka"

 Dim SingleValue() As String
 SingleValue = Split(StringValue, " ")

 MsgBox SingleValue(0) & vbNewLine & SingleValue(1) & vbNewLine
 & SingleValue(2) & vbNewLine & SingleValue(3) & _vbNewLine &
 SingleValue(4) & vbNewLine & SingleValue(5) & vbNewLine & SingleValue(6)

End Sub

Now, run the code and see what we get in the message box.

Example 1-6

Each and every word has been split into arrays.

Example #2

Now, imagine a situation of storing these values in cells, i.e., each word in a separate cell. For this, we need to include the 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.

The below code will insert each word into separate cells.

Sub String_To_Array1()

 Dim StringValue As String
 StringValue = "Bangalore is the capital city of Karnataka"

 Dim SingleValue() As String
 SingleValue = Split(StringValue, " ")

 Dim k As Integer

 For k = 1 To 7
  Cells(1, k).Value = SingleValue(k - 1)
 Next k

End Sub

It will insert each word, as shown in the below image.

Example 2

Things to Remember

  • One may use arrays and loops to make the code dynamic.
  • The SPLIT function requires a common delimiter, which separates each word in the sentence.
  • Array length starts from zero, not from 1.

Recommended Articles

This article has been a guide to VBA Split String into Array. Here, we discuss converting a split string into an array in Excel VBA, along with practical examples. You can learn more about VBA functions from the following articles: –

  • Split Names in Excel
  • VBA String Comparison
  • Excel VBA String Array
  • Find Next in VBA

To split a string into an array of sub-strings of any desired length:

Function charSplitMulti(s As Variant, splitLen As Long) As Variant
    
        Dim padding As Long: padding = 0
        Dim l As Long: l = 0
        Dim v As Variant
        
        'Pad the string so it divides evenly by
        ' the length of the desired sub-strings
        Do While Len(s) Mod splitLen > 0
            s = s & "x"
            padding = padding + 1
        Loop
        
        'Create an array with sufficient
        ' elements to hold all the sub-strings
        Do Until Len(v) = (Len(s) / splitLen) - 1
            v = v & ","
        Loop
        v = Split(v, ",")
        
        'Populate the array by repeatedly
        ' adding in the first [splitLen]
        ' characters of the string, then
        ' removing them from the string
        Do While Not s Like ""
            v(l) = Mid(s, 1, splitLen)
            s = Right(s, Len(s) - splitLen)
            l = l + 1
        Loop
        
        'Remove any padding characters added at step one
        v(UBound(v)) = Left(v(UBound(v)), Len(v(UBound(v))) - padding)
        
        'Output the array
        charSplitMulti = v
    
    End Function

You can pass the string into it either as a string:

Sub test_charSplitMulti_stringInput()

    Dim s As String: s = "123456789abc"
    Dim subStrLen As Long: subStrLen = 4
    Dim myArray As Variant
    
    myArray = charSplitMulti(s, subStrLen)
    
    For i = 0 To UBound(myArray)
        MsgBox myArray(i)
    Next

End Sub

…or already declard as a variant:

Sub test_charSplitMulti_variantInput()

    Dim s As Variant: s = "123456789abc"
    Dim subStrLen As Long: subStrLen = 5
    
    s = charSplitMulti(s, subStrLen)
    
    For i = 0 To UBound(s)
        MsgBox s(i)
    Next

End Sub

If the length of the desired sub-string doesn’t divide equally into the length of the string, the uppermost element of the array will be shorter. (It’ll be equal to strLength Mod subStrLength. Which is probably obvious.)

I found that most-often I use it to split a string into single characters, so I added another function, so I can be lazy and not have to pass two variables in that case:

Function charSplit(s As Variant) As Variant

    charSplit = charSplitMulti(s, 1)

End Function

Sub test_charSplit()

    Dim s As String: s = "123456789abc"
    Dim myArray As Variant
    
    myArray = charSplit(s)
    
    For i = 0 To UBound(myArray)
        MsgBox myArray(i)
    Next

End Sub

Return to VBA Code Examples

In this Article

  • Declaring a String variable
  • Declaring a Static String Array
  • Declaring a Variant Array using the Array function
  • Declaring a String Array using the Split Function

This tutorial will teach you how to declare and initialize a string array in VBA.

Declaring a String variable

When you declare a string variable in VBA, you populate it by adding a single string to the variable which you can then use in your VBA code.

Dim strName as String
StrName = "Bob Smith"

Declaring a Static String Array

If you want to populate an array with a string of values, you can create a STATIC string array to do so.

Dim StrName(2) as String 
StrName(0) = "Bob Smith"
StrName(1) = "Tom Jones"
StrName(2) = "Mel Jenkins"

Remember that the Index of an Array begins at zero – so we declare the Array size to be 2 – which then enables the Array to hold 3 values.

Instead, you can explicitly define the start and end positions of an array:

Dim StrName(1 to 3) as String 
StrName(1) = "Bob Smith"
StrName(2) = "Tom Jones"
StrName(3) = "Mel Jenkins"

Declaring a Variant Array using the Array function

If you want to populate an array with a string of values without implicitly stating the size of the Array, you can create a variant array and populate it using the Array function.

Dim strName as Variant
strName = Array("Bob Smith", "Tom Jones", "Mel Jenkins")

Declaring a String Array using the Split Function

If you want to keep the variable as a string but do not want to implicitly state the size of the Array, you would need to use the Split function to populate the array.

Dim strName() as String 
strNames = Split("Bob Smith, Tom Jones, Mel Jenkins")

The Split function allows you to keep the data type (eg String) while splitting the data into the individual values.

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!
vba save as

Learn More!

Example

Split Function

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

Syntax

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

Part Description
expression Required. String expression containing substrings and delimiters. If expression is a zero-length string(«» or vbNullString), Split returns an empty array containing no elements and no data. In this case, the returned array will have a LBound of 0 and a UBound of -1.
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
Description -1 Performs a comparison 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

In this example it is demonstrated how Split works by showing several styles. The comments will show the result set for each of the different performed Split options. Finally it is demonstrated how to loop over the returned string array.

Sub Test
    
    Dim textArray() as String

    textArray = Split("Tech on the Net")
    'Result: {"Tech", "on", "the", "Net"}

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

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

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

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

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

    textArray = Split("A;B;C;D", ";", 4)
    'Result: {"A", "B", "C", "D"}

    'You can iterate over the created array
    Dim counter As Long

    For counter = LBound(textArray) To UBound(textArray)
        Debug.Print textArray(counter)
    Next
 End Sub

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

Ситуация: дана строка, в которой через запятую перечислены значения (или диапазоны значений)

Требуется подсчитать, сколько значений содержится в строке, или же разбить строку на массив, содержащий все значения из исходной строки.

И, если при исходных строках вида «5,6,8,18,2,21» всё просто (достаточно применить VB-функцию Split), то при наличии в строке диапазонов значений вида Число1-Число2 (например, строка «9-15,18,2,11-9«) задача заметно усложняется.

В этих случаях на помощь придёт функция ArrayOfValues

Function ArrayOfValues(ByVal txt$) As Variant
 
' Принимает в качестве параметра строку типа ",,5,6,8,,9-15,18,2,11-9,,1,4,,21,"
    ' Возвращает одномерный (горизонтальный) массив в формате
    ' array(5,6,8,9,10,11,12,13,14,15,18,2,11,10,9,1,4,21)
    ' (пустые значения удаляются; диапазоны типа 9-15 и 17-13 раскрываются)

arr = Split(Replace(txt$, " ", ""), ","): Dim n As Long: ReDim tmpArr(0 To 0)
    For i = LBound(arr) To UBound(arr)
        Select Case True
            Case arr(i) = "", Val(arr(i)) < 0
                '  раскомментируйте эту строку, чтобы пустые и нулевые значения
                '  тоже добавлялись в результат (преобразовывались в значение -1)
                'tmpArr(UBound(tmpArr)) = -1: ReDim Preserve tmpArr(0 To UBound(tmpArr) + 1)
            Case IsNumeric(arr(i))
                tmpArr(UBound(tmpArr)) = arr(i): ReDim Preserve tmpArr(0 To UBound(tmpArr) + 1)
            Case arr(i) Like "*#-#*"
                spl = Split(arr(i), "-")
                If UBound(spl) = 1 Then
                    If IsNumeric(spl(0)) And IsNumeric(spl(1)) Then
                        For j = Val(spl(0)) To Val(spl(1)) Step IIf(Val(spl(0)) > Val(spl(1)), -1, 1)
                            tmpArr(UBound(tmpArr)) = j: ReDim Preserve tmpArr(0 To UBound(tmpArr) + 1)
                        Next j
                    End If
                End If
        End Select
    Next i
    On Error Resume Next: ReDim Preserve tmpArr(0 To UBound(tmpArr) - 1)
    ArrayOfValues = tmpArr
End Function

Использовать её можно так:

Sub ПримерИспользования()
    ' разбиваем строку в массив, содержащий все значения исходной строки
    a = ArrayOfValues(",,5,6,8,,9-15,18,2,11-9,,1,4,,21,")
 
    Debug.Print Join(a, ",") ' объединяем обратно созданный массив
    ' результатом будет строка "5,6,8,9,10,11,12,13,14,15,18,2,11,10,9,1,4,21"
End Sub

Функция нашла применение в программе выгрузки тарифов в XML


Ещё один вариант функции, только она возвращает из аналогичной текстовой строки КОЛЛЕКЦИЮ НЕПОВТОРЯЮЩИХСЯ чисел от 1 до 255

Function ArrayOfValuesEx(ByVal txt$) As Collection
    ' Принимает в качестве параметра строку типа ",,5,6,8,,9-15,18,2,11-9,,1,4,,21,"
    ' Возвращает колекцию уникальных чисел в формате    (5,6,8,9,10,11,12,13,14,15,18,2,1,4,21)
    ' (удаляются все значения кроме целых чисел от 1 до 255; диапазоны типа 9-15 и 17-13 раскрываются)

    On Error Resume Next: Set ArrayOfValuesEx = New Collection
    MaxNumber& = 255
    txt = Replace(Replace(txt, ".", ","), " ", "")
    For i = 1 To Len(txt)
        If Mid(txt, i, 1) Like "[0-9,-]" Then res = res & Mid(txt, i, 1) Else res = res & " "
    Next
    txt = Replace(res, " ", "")
 
    arr = Split(txt, ","):
    For i = LBound(arr) To UBound(arr)
        Select Case True
            Case arr(i) = "", Val(arr(i)) < 0
            Case IsNumeric(arr(i))
                v& = Val(arr(i)): If v > 0 And v <= MaxNumber& Then ArrayOfValuesEx.Add v, CStr(v)
            Case arr(i) Like "*#-#*"
                spl = Split(arr(i), "-")
                If UBound(spl) = 1 Then
                    If IsNumeric(spl(0)) And IsNumeric(spl(1)) Then
                        For j = Val(spl(0)) To Val(spl(1)) Step IIf(Val(spl(0)) > Val(spl(1)), -1, 1)
                            v& = j: If v > 0 And v <= MaxNumber& Then ArrayOfValuesEx.Add v, CStr(v)
                        Next j
                    End If
                End If
        End Select
    Next i
End Function
 
Private Sub ArrayOfValuesEx_ПримерИспользования()
    ' разбиваем строку в массив, содержащий все значения исходной строки
    Dim coll As Collection
    Set coll = ArrayOfValuesEx(",,5,6,+8,,9-12,18//,2,11-9,,1,4.6,,21,7a,ajsgh55,4-")
 
    For Each Item In coll: Debug.Print Item;: Next: Debug.Print
    ' результатом будет   5  6  8  9  10  11  12  18  2  1  4  21  7  55
End Sub
  • 20634 просмотра

Не получается применить макрос? Не удаётся изменить код под свои нужды?

Оформите заказ у нас на сайте, не забыв прикрепить примеры файлов, и описать, что и как должно работать.

VBA String Array

Excel VBA String Array

When we have multiple variables to be declared in a VBA Code, we can declare the exact number of a variable with data type we want. But this process is quite lengthy when the variable count goes above 5. Why declare variables multiple times when we can frame that into String Array. A VBA String Array is used when we need to hold more than one string value with a string variable. This looks tricky but in reality, it is very easy to implement. We don’t have to declare one type of variable multiple times if each variable store’s different values. This slash in a huge VBA Code is done using Excel VBA String Array.

How to Use VBA String Array?

To use VBA String Array in any code, it is very simple. For this, we just need to define how many variables we will require. This will be first done using DIM. Suppose, if we want 10 variables of any data type so that could be done as shown below.

Code:

Sub VBA_StringArray()

Dim NameOfVariable(1 To 10) As DataType

End Sub

VBA String Array Examples

We can choose any name in place Name Of Variable and any data type in Data Type box as highlighted above.

Examples of String Array in Excel VBA

Below are the examples of an excel VBA string array.

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

Example #1

In this example, we will see how to use String Array in VBA without any limit in variables. Here, we will not define the length of variables, instead, we will directly create string array and use the number of variables as we our need. For this, follow the below steps:

Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.

Insert Module

Step 2: Define the subprocedure preferably in the name of VBA String Array or we can choose any name as per our choice.

Code:

Sub VBA_StringArray1()

End Sub

VBA String Array Examples 1-1

Step 3: Now we will be using Employee names for creating the array. For this declare a variable in a similar name and put brackets “( )” after that. And choose any data type. We can choose String or Integer or Variant. But as the data may vary so using Variant will be good.

Code:

Sub VBA_StringArray1()

Dim EmployeeData() As Variant

End Sub

Variant Examples 1-2

Step 4: Now use the same variable which we declared above and use Array function.

Code:

Sub VBA_StringArray1()

Dim EmployeeData() As Variant
EmployeeData = Array(

End Sub

VBA String Array Examples 1-3

As we can see, as per the syntax of Array, it only allows Variant data type and Argument List (). The reason for seeing the Variant data type is because we can store any type of value in it.

Step 5: Now consider the names of employees which we will be using here. We have Anand, Shraddha, Aniket, Ashwani, and Deepinder as Employee names. And it should be in the way as we do concatenation.

Code:

Sub VBA_StringArray1()

Dim EmployeeData() As Variant
EmployeeData = Array("Anand", "Shraddha", "Aniket", "Ashwani", "Deepinder")

End Sub

Employee names Examples 1-4

Step 6: And to print the values stored in the Employee Data array we will use MsgBox. And array will be in the sequence of numbers at which we have defined.

Code:

Sub VBA_StringArray1()

Dim EmployeeData() As Variant
EmployeeData = Array("Anand", "Shraddha", "Aniket", "Ashwani", "Deepinder")
MsgBox EmployeeData(0) & ", " & EmployeeData(1) & ", " & EmployeeData(3) & ", " & EmployeeData(4)

End Sub

VBA String Array Examples 1-6

Step 7: Run this code by hitting the F5 or Run button which is placed on the topmost ribbon of VBE.

Run button Example

Step 8: We will get the message box with all the employee names in the sequence we put it.

VBA String Array Examples 1-8

Step 9: Let’s try to change the sequence of Employee Data array. Here we have exchanged 0 and 4 with each other.

Code:

Sub VBA_StringArray1()

Dim EmployeeData() As Variant
EmployeeData = Array("Anand", "Shraddha", "Aniket", "Ashwani", "Deepinder")
MsgBox EmployeeData(4) & ", " & EmployeeData(1) & ", " & EmployeeData(3) & ", " & EmployeeData(0)

End Sub

Employee names Examples 1-9

Step 10: Let’s run this code again. We will notice, Employee Data name Deepinder is now moved to first place and Anand is at 4th place.

VBA String Array Examples 1-6

Example #2

In this example, we will set the position of cells in the array and get the combination of output by that. For this, we will use the same employee names which we have seen in. For this, follow the below steps:

Step 1: Write the subprocedure.

Code:

Sub VBA_StringEmployeDataay2()

End Sub

VBA String Array Examples 2-1

Step 2: Define a variable as Variant with cell positioning as (1, 3) Which 1 shows the 2nd position.

Code:

Sub VBA_StringEmployeDataay2()

Dim EmployeData(1, 3) As Variant

End Sub

VBA String Array Examples 2-2

Step 3: Now we will assign each employee name to different co-ordinates. Such as, at 1st row, 2nd column we have set employee Anand.

Code:

Sub VBA_StringEmployeDataay2()

Dim EmployeData(1, 3) As Variant
EmployeData(0, 1) = "Anand"

End Sub

VBA String Array Examples 2-3

Step 4: Similarly we will choose different co-ordinates from (1, 3) position and give each employee name in a different position.

Code:

Sub VBA_StringEmployeDataay2()

Dim EmployeData(1, 3) As Variant
EmployeData(0, 1) = "Anand"
EmployeData(0, 2) = "Shraddha"
EmployeData(1, 2) = "Aniket"
EmployeData(1, 3) = "Ashwani"
EmployeData(0, 0) = "Deepinder"

End Sub

VBA String Array Examples 2-4

Now to get the output from the defined array, we will use the message box.

Step 5: We have used the position of co-ordinates. Such as for (0, 1).

Code:

Sub VBA_StringEmployeDataay2()

Dim EmployeData(1, 3) As Variant
EmployeData(0, 1) = "Anand"
EmployeData(0, 2) = "Shraddha"
EmployeData(1, 2) = "Aniket"
EmployeData(1, 3) = "Ashwani"
EmployeData(0, 0) = "Deepinder"
MsgBox ("EmployeData In Index 0,1 : " & EmployeData(0, 1))

End Sub

VBA String Array Examples 2-5

Step 6: Similarly, another message box to see other values stored in different co-ordinates.

Code:

Sub VBA_StringEmployeDataay2()

Dim EmployeData(1, 3) As Variant
EmployeData(0, 1) = "Anand"
EmployeData(0, 2) = "Shraddha"
EmployeData(1, 2) = "Aniket"
EmployeData(1, 3) = "Ashwani"
EmployeData(0, 0) = "Deepinder"
MsgBox ("EmployeData In Index 0,1 : " & EmployeData(0, 1))
MsgBox ("EmployeData In Index 1,2 : " & EmployeData(1, 2))

End Sub

VBA String Array Examples 2-6

Step 7: Once done, compile the code by hitting the F8 or Run button. We will see, the values stored in the array (0, 1) is Anand.

Message Box Examples 2-7

Step 8: And the second array (1, 2) stores the value as Aniket.

Message Box Examples 2-8

This is how co-ordinating in String array works.

Step 9: What if we change the array co-ordinates for the second message box from (1, 2) to (2, 2).

Code:

Sub VBA_StringEmployeDataay2()

Dim EmployeData(1, 3) As Variant
EmployeData(0, 1) = "Anand"
EmployeData(0, 2) = "Shraddha"
EmployeData(1, 2) = "Aniket"
EmployeData(1, 3) = "Ashwani"
EmployeData(0, 0) = "Deepinder"
MsgBox ("EmployeData In Index 0,1 : " & EmployeData(0, 1))
MsgBox ("EmployeData In Index 1,2 : " & EmployeData(2, 2))

End Sub

VBA String Array Examples 2-9

Step 10: We will see, once the first array message box shows the value, the second message box will give the error, as Subscript Out Of range. Which means, we have selected the range which either incorrect or not exists.

VBA String Array Examples 2-10

Pros of VBA String Array:

  • VBA String Array can hold any type of value.
  • There is no limit to storage capacity in String Array.

Things to Remember

  • We can create 2D and 3D String array both.
  • Called value of array should be in the range of defined values.
  • It is not advised to fix the length of the array. Because if the value of an array is out of range, then we will end up getting the error.
  • Also, save the file in macro enable excel format to preserve the written VBA Code.
  • We can use different functions such as LBOUND, UBOUND, Split, Join, Filter, etc. in String Arrays using Loops.

Recommended Articles

This is a guide to the VBA String Array. Here we discuss how to use String Array in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA SendKeys
  2. VBA Name Worksheet
  3. VBA CInt
  4. VBA SubString

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

Home / VBA / Arrays / VBA Array with Strings

In VBA, you can create an array with strings where each element of the array stores one string that you can further access or even combine into one string. Apart from this, you can also split the main string into multiple sub-strings (using a delimiter) and then store each of them into the array’s elements.

As I said above, there are two ways to use strings in an array, and in this tutorial, we will see how to write code for both.

Option Base 1
Sub vba_string_array()

Dim myArray() As Variant
myArray = Array("One", "Two", "Three")
   
Debug.Print myArray(1)
Debug.Print myArray(2)
Debug.Print myArray(3)
      
End Sub
  1. First, declare an array without the element count that you want to store in there.
  2. Next, you need to use VBA’s ARRAY function to define the value that you want to specify.
  3. After that, specify all the strings using a comma into the function.
  4. In the end, you can access all the strings using the element number.

In the same way, you can also get a string from the cells to store in the array.

VBA Split String and Store in an Array

If you want a string that has multiple substrings you can split it using the VBA’s SPLIT function which uses a delimiter.

Option Base 1
Sub vba_string_array()

Dim myArray() As String
myArray = Split("Today is a good day", " ")
For i = LBound(myArray) To UBound(myArray)
    Debug.Print myArray(i)
Next i
      
End Sub

In this code, you have a string which is a sentence that has five words. And when you use the split function it splits it into five different substrings, and then you have stored it in the elements of the array.

After that, you have the for loop which uses the upper and lower bound for the counter to loop and prints each element of the array into the immediate window.

Понравилась статья? Поделить с друзьями:
  • Vba excel строка в двойных кавычках
  • Vba excel столбец умной таблицы в массив
  • Vba excel столбец по номеру
  • Vba excel столбец по имени
  • Vba excel столбец массива в excel