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

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

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

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

И, если при исходных строках вида «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
  • 20631 просмотр

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

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

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

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

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

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