Change variables using array

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… ?
 
D

Douglas J. Steele

I don't understand what you mean by "an array of variables". Can you give a
more complete example?
 
G

Guest

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.
 
D

Douglas J. Steele

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)
 
G

Guest

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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top