Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate VBA Array with list of values in native code

Tags:

excel

vba

Hoping there is a quick answer to this question....

I have an array and I want to populate it with a list of arguments.

Sub EasyArrayInput()
Dim myArr() as variant
myArr = ("string1", "string2", "string3")
End Sub

I am well aware of how to loop through and populate with a for/next or do/while, but it would be nice to be able to populate an array when the values wont change without using a hardcoded method.

Sub UsualMethodThatIDontWantToDo()
Dim myArr(1 to 3) as variant
myArr(1) =  "string1"
myArr(2) =  "string2"
myArr(3) =  "string3"
End Sub

Is there anyway to do it in a method similar to the first code snippet? I would prefer to do it that way. I apologize if this question has been asked/answered, but I'm not quite sure what the method I am asking about is called.

Thanks in advance!

Edit: Solution

The code snippet below (from the link that chancea sent) will create an array that is a variant and exaclty what I wanted.

Sub EasyArrayInput()
Dim myArr() as variant
myArr = Array("string1", "string2", "string3")
End Sub

The next code snippet looks to be useful for if you only have strings and don't want to initialize a variant:

Sub EasyArrayInput()
Dim myArr() as String
myArr = Split("String1,String2,String3", ",")
End Sub
like image 760
JSS Avatar asked Feb 19 '15 16:02

JSS


People also ask

How do I add values to an array in Excel VBA?

Add a New Value to an Array in VBA First, you need to use the “ReDim” statement with the “Preserve” keyword to preserve the two elements including the new element for which you want to add the value. Next, you need to define the elements that you want to have in the array.

How do you assign a range to an array in VBA?

Steps to Add a Range into an Array in VBA First, you need to declare a dynamic array using the variant data type. Next, you need to declare one more variable to store the count of the cells from the range and use that counter for the loop as well. After that, assign the range where you have value to the array.


2 Answers

How about?

Sub EasyArrayInput()
    Dim myArr() As Variant

    myArr = Array("string1", "string2", "string3")
End Sub
like image 162
basodre Avatar answered Oct 14 '22 05:10

basodre


Assuming you have some sort of numeric sequence, you can do something like this:

Dim myArray()
myArray = [TRANSPOSE(INDEX("string"&ROW(1:10),))]

but frankly I think a loop is clearer.

like image 2
Rory Avatar answered Oct 14 '22 05:10

Rory