Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vba better way to set all values in array to same thing

Tags:

excel

vba

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.

like image 522
Alec Avatar asked May 22 '12 15:05

Alec


People also ask

How do you assign a range of cells 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.

How do I create a dynamic array in VBA?

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.

Why are collections better than arrays VBA?

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.

What is a variant array VBA?

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.


2 Answers

I'm not very good at drawing images. But this should give you and make clear the concepts associated with variant arrays.

variant versus variant array

like image 110
Pradeep Kumar Avatar answered Nov 03 '22 01:11

Pradeep Kumar


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
like image 40
Siddharth Rout Avatar answered Nov 03 '22 01:11

Siddharth Rout