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.
Dim cell As Range
Dim val As Variant
For Each cell In Range("packing_list[Code]")
val = cell.Value
Next cell
MsgBox Join(val, "//")
and
Dim oSh As Worksheet
Dim CodeRange As Variant
Set oSh = ActiveSheet
CodeRange = oSh.Range("packing_list[Code]").Value
MsgBox Join(CodeRange , "//")
They both error on the MsgBox line. What do I do wrong ?
Thanks
braX
11.5k5 gold badges20 silver badges33 bronze badges
asked Dec 10, 2015 at 12:59
3
The value you are trying to join is not an array of strings. Join is supposed to be used on arrays
Here is the link to the Microsoft instructions: https://msdn.microsoft.com/en-us/library/b65z3h4h%28v=vs.90%29.aspx
Their example is:
Dim TestItem() As String = {"Pickle", "Pineapple", "Papaya"}
Dim TestShoppingList As String = Join(TestItem, ", ")
You code should look something like:
Dim i As Integer
Dim cell As Range
Dim val() As Variant '() indicate it is an array
i = 0
For Each cell In Range("packing_list[Code]")
ReDim Preserve val(0 to i) As Variant 'must resize array to fit number of items
val(i) = cell.Value 'i is the position of the item in the array
i = i + 1 'increment i to move to next position
Next cell
'Now that you have an array of values (i.e. ("String1", "String2", ...) instead of just "String" you can:
MsgBox Join(val, "//")
answered Dec 10, 2015 at 13:05
4
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
MsgBox Join(Application.Transpose([a1:a10]), ",")
to work on a row you need a second Transpose
, so for A1:K1
MsgBox Join(Application.Transpose(Application.Transpose([a1:k1])), ",")
answered Dec 11, 2015 at 3:29
brettdjbrettdj
54.6k16 gold badges113 silver badges176 bronze badges
1
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
See this:
How do I declare an array variable in VBA?
As @Brandon Keck says, Join is expecting an Array.
answered Dec 10, 2015 at 13:21
Simon WraySimon Wray
1924 silver badges12 bronze badges
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:
[:] AND [:=1]
I get
[Surname:=Gedye,=Sole,=Williams] AND [Active:=1]
Public Function AutoFilterCriteria(ByVal WholeTable As Range) As String
On Error Resume Next
If WholeTable.Parent.AutoFilter Is Nothing Then ' if no filter is applied
AutoFilterCriteria = "None"
On Error GoTo 0
Exit Function
End If
Dim LongStr As String, FirstOne As Boolean
LongStr = ""
FirstOne = False
Dim iFilt As Integer
For iFilt = 1 To WholeTable.Parent.AutoFilter.Filters.Count ' loop through each column of the table
Dim ThisFilt As Filter
Set ThisFilt = WholeTable.Parent.AutoFilter.Filters(iFilt) ' look at each filter
On Error Resume Next
With ThisFilt
If .On Then
If FirstOne Then LongStr = LongStr & " AND " ' Get column title
'The line below was modified from the original
LongStr = LongStr & "[" & Range("MainTable[#Headers]")(1, iFilt)
LongStr = LongStr & WholeTable.Parent.Cells(WholeTable.Row - 1, WholeTable.Column + iFilt - 1).Value & ":"
On Error GoTo Handle
If .Operator = xlFilterValues Then ' dont really care to enumerate multiples, just show "multiple"
'The line below was modified from the original
LongStr = LongStr & Join(.Criteria1, ",") & "]"
ElseIf .Operator = 0 Then
LongStr = LongStr & .Criteria1 & "]"
ElseIf .Operator = xlAnd Then
LongStr = LongStr & .Criteria1 & " AND " & .Criteria2 & "]"
ElseIf .Operator = xlOr Then
LongStr = LongStr & .Criteria1 & " OR " & .Criteria2 & "]"
End If
On Error GoTo 0
FirstOne = True
End If
End With
Next
AutoFilterCriteria = LongStr
On Error GoTo 0
Exit Function
Handle:
AutoFilterCriteria = "! Error !"
On Error GoTo 0
End Function
answered Dec 8, 2021 at 0:38
1
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
Содержание
- Преобразование массива в строку
- Преобразование строки в массив
- Split function
- Syntax
- Settings
- Example
- See also
- Support and feedback
- Функция Split
- Синтаксис
- Параметры
- Пример
- См. также
- Поддержка и обратная связь
- VBA String Array
- Excel VBA String Array
- Examples of String Array in Excel VBA
- Example #1
- Example #2
- Example #3
- Things to Remember
- Recommended Articles
- Convert Variable Array to String
- 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]
Источник
Преобразование массива в строку |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
jfd Пользователь Сообщений: 302 |
Доброй ночи (утра) Изменено: jfd — 14.01.2016 01:29:16 |
vikttur Пользователь Сообщений: 47199 |
|
jfd Пользователь Сообщений: 302 |
vikttur, не понял если честно если надо перенести на лист «строку» массива, нужно ли ее транспонировать? Изменено: jfd — 14.01.2016 00:39:28 |
Все_просто Пользователь Сообщений: 1042 |
#4 14.01.2016 00:48:49 Вот это вставляет содержимое массива на лист начиная с ячейки А4
Вот это вставляет содержимое первой строки на лист начиная с ячейки А4
Изменено: Все_просто — 14.01.2016 00:50:56 С уважением, |
||||
KL Пользователь Сообщений: 2186 |
#5 14.01.2016 00:52:19 Так?
KL |
||
vikttur Пользователь Сообщений: 47199 |
#6 14.01.2016 00:53:04
|
||
jfd Пользователь Сообщений: 302 |
Все_просто,нет, в вашем решении у меня выгрузило весь массив по вертикали и горизонтали на лист, где верхнее левое значение Arr(1,1) оказалось в ячейке A4. ПС. Второй вариант именно то что надо, кажется. Не заметил исправления вашего поста. Можно его немного поподробнее разобрать? Можно вставить не первую «строку» массива, а например 2ю или 3ю? Изменено: jfd — 14.01.2016 01:30:41 |
jfd Пользователь Сообщений: 302 |
vikttur,извините меня, думаю одно пишу другое, хочу правильного решения. исправил первоначальный пост |
jfd Пользователь Сообщений: 302 |
#9 14.01.2016 01:35:20 KL, то что надо. Спасибо |