Vba is the best way to set all values ​​in an array to the same thing

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 it:

r(0)=-1
r(1)=-1

Or I could iterate through a loop and set them to -1.

So my question is, is it possible to somehow set all the values ​​in the array to the same thing without repeating?

Or, I can do something like:

r = array(-1,-1)

This may be a really stupid question, but I cannot find the answer.

+5
source share
2 answers

Yes you can do it. But then you have to take care declaring an 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

. Excel:) Array Variant, array. . , .

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
+5

. , .

variant versus variant array

+8

All Articles