Change variables using array

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I frequently us an array to change the value of check boxes as follows:

Dim i As Integer
Dim j As String
Dim aryChk As Variant
aryChk = Array("A", "B", "C", "D")
For i = 0 To 3
j = "chk" & aryChk(i)
Me(j).Value = 0
Next i

Is there a way to similarly change the values of an array of variables, say
varA, varB, varC… ?
 
I don't understand what you mean by "an array of variables". Can you give a
more complete example?
 
Thanks Doug,

I wanted to change the value of integer variables varA, varB, varC,… to 1.
I started to use the same process I used to change the values of an array of
check boxes as follows:

Dim i As Integer
Dim j As String
Dim aryVar As Variant
aryVar = Array("A", "B", "C", "D")
For i = 0 To 3
j = "var" & aryChk(i)
Me(j).Value = 1
Next i

Then I realized this just changes the value of j and not the variable I
assigned to j.
 
VBA doesn't allow indirect referencing like that.

Why not use an array, though? Rather than varA, varB, varC and varD, create
an array aryValues. If it makes it easier for you to call them varA, varB,
varC and varD, you can create constants with that value so that you can
refer to varValues(varA) if you want.

Const varA As Integer = 0
Const varB As Integer = 1
Const varC As Integer = 2
Const varD As Integer = 3

Dim i As Integer
Dim j As String
Dim aryValues(0 to 3) As Integer

For i = 0 To 3
aryValues(i) = 1
Next i

Now, you can use aryValues(varA), aryValues(varB), aryValues(varC) and
aryValues(varD)
 
Thanks Doug,
Thats just what I needed!

Douglas J. Steele said:
VBA doesn't allow indirect referencing like that.

Why not use an array, though? Rather than varA, varB, varC and varD, create
an array aryValues. If it makes it easier for you to call them varA, varB,
varC and varD, you can create constants with that value so that you can
refer to varValues(varA) if you want.

Const varA As Integer = 0
Const varB As Integer = 1
Const varC As Integer = 2
Const varD As Integer = 3

Dim i As Integer
Dim j As String
Dim aryValues(0 to 3) As Integer

For i = 0 To 3
aryValues(i) = 1
Next i

Now, you can use aryValues(varA), aryValues(varB), aryValues(varC) and
aryValues(varD)
 
Back
Top