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?
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 .
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.
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.
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.
Try this:
' Variant array
Dim myVariantArray As Variant
myVariantArray = Array("Cat", "Dog", "Rabbit")
' String array
Dim myStringArray() As String
myStringArray = Split("Cat,Dog,Rabbit", ",")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With