Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA: Change value of variables in an array

Tags:

arrays

excel

vba

How do I permanently change the value of a variable in an array? I wrote some code that illustrates my problem:

Option Explicit
    Dim var1 As Boolean, var2 As Boolean, var3 As Boolean

Sub Test()
    Dim arrTest As Variant
    Dim i

    arrTest = Array(var1, var2, var3)

    For Each i In arrTest
        Debug.Print i
    Next

    For i = LBound(arrTest) To UBound(arrTest)
        arrTest(i) = True
    Next

    For Each i In arrTest
        Debug.Print i
    Next

    Test2
End Sub


Sub Test2()
    Debug.Print "var1 in Sub Test2 : " & var1
    If var1 Then
        Debug.Print "Hello"
    End If
End Sub

The output in the direct window is:

False
False
False
True
True
True
var1 in Sub Test2 : False

The first six lines make sense to me because I changed the value of the variables in Test. However, it obviously wasn't permanent or it was confined to that one sub and so "Hello" in Test2 didn't get printed.

How do I change this? I've read that for each loops are read-only, but why does the for-loop not work?

like image 925
Alex Avatar asked Aug 28 '19 07:08

Alex


2 Answers

Assigning "True" to every element of array does not make your variables same value. Nothing weird your var1 is still False, because You didn't change the value of var1, but the value of your array elements. :)

Add something like this

var1 = arrTest(0)
var2 = arrTest(1)
var3 = arrTest(2)

Test2
like image 122
Teamothy Avatar answered Oct 13 '22 05:10

Teamothy


When you do arrTest = Array(var1, var2, var3) you copy the values of your variables into the arrTest. You do NOT create a reference to those variables.

Since arrTest is declared in Test() its scope is limited to Test().

If you declare arrTest at the module level, you will be able to check arrTest values from Test2. But anyway they will be completely independent from varx.

The behaviour is different if we speak about Objects. When we write Set x = obj1 we DO create a reference, and in that case a change in obj1 will be visible in x.

like image 40
iDevlop Avatar answered Oct 13 '22 04:10

iDevlop