This is a matter of personal curiosity.
In VBA, if I have an array of size 2:
Dim r(1) as Variant
And I want both values in the array to be -1. I can do this:
r(0)=-1
r(1)=-1
Or I could iterate through both with a loop and set them to -1.
So my question is, is there any way I can set all the values in an array to the same thing without iterating?
Or, is there any way I can do something like:
r = array(-1,-1)
This might be a really stupid question but I can't seem to find the answer.
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.
Create a Dynamic Array in VBAFirst, declare an array with its name. After that, the elements count left the parentheses empty. Now, use the ReDim statement. In the end, specify the count of elements you want to add to the array.
Unlike arrays, a single collection can store items of different types because each item in a collection is stored as a Variant. Many developers use collections instead of arrays for storing groups of related items to eliminate the hassles and extra code to set and verify array bounds.
Arrays are a variant type variable that you can use in VBA coding to store a list of data. Think of it as a mini-spreadsheet inside of a single variable. You store data into an array by referring to a reference number that corresponds with the location that the piece of data is positioned in.
I'm not very good at drawing images. But this should give you and make clear the concepts associated with variant arrays.
Yes you can do it. But then you have to take care while declaring the array
Example
Option Explicit
Sub Sample()
Dim r As Variant '<~~
r = Array(-1, -1)
Debug.Print r(0)
Debug.Print r(1)
End Sub
FOLLOWUP
See the Excel Help File :) The Array Function returns a Variant
containing an array
. You cannot assign an array to another array directly. To assign an array to another array you have to use this method.
Option Explicit
Sub Sample()
Dim r(1) As Variant
Dim s As Variant
Dim i As Long
s = Array(-1, -1)
For i = LBound(r) To UBound(r)
r(i) = s(i)
Next
Debug.Print r(0)
Debug.Print r(1)
End Sub
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