Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare and Initialize String Array in VBA

This should work according to another stack overflow post but its not:

Dim arrWsNames As String() = {"Value1", "Value2"}

Can anyone let me know what is wrong?

like image 454
Kairan Avatar asked Oct 14 '22 02:10

Kairan


People also ask

How do I declare and initialize a string array in Excel VBA?

you have to declare the bounderies of the array. Either a dynamic Array : Dim MyArray() as String , or a fixed size Array : Dim MyArray(1 to 10) as String .

How do I create an array of strings in VBA?

First, declare an array without the element count that you want to store in there. Next, you need to use VBA's ARRAY function to define the value that you want to specify. After that, specify all the strings using a comma into the function. In the end, you can access all the strings using the element number.

How do I initialize a string in VBA?

To initialize a string variable, place the string value within double quotes. : String « Data Type « VBA / Excel / Access / Word. To initialize a string variable, place the string value within double quotes.

How do I initialize an array in Excel VBA?

To initialize an array variable by using an array literalIf you supply both the upper bound and the values, you must include a value for every element from index 0 through the upper bound. Notice that you do not have to specify the index upper bound if you supply element values in an array literal.


2 Answers

Try this:

' Variant array    
Dim myVariantArray As Variant
myVariantArray = Array("Cat", "Dog", "Rabbit")

' String array
Dim myStringArray() As String
myStringArray = Split("Cat,Dog,Rabbit", ",")
like image 204
Eldar Agalarov Avatar answered Oct 16 '22 23:10

Eldar Agalarov


In the specific case of a String array you could initialize the array using the Split Function as it returns a String array rather than a Variant array:

Dim arrWsNames() As String
arrWsNames = Split("Value1,Value2,Value3", ",")

This allows you to avoid using the Variant data type and preserve the desired type for arrWsNames.

like image 173
Aiken Avatar answered Oct 16 '22 22:10

Aiken