Referring to a sequentially created variable

JGalletta

Windows 7 Access 2010
Local time
Today, 14:49
Joined
Feb 9, 2012
Messages
149
I've declared the following:

Code:
Dim C(12) As String

I have a loop that takes the number part of a control name using:

Code:
Right(controlname, Len(controlname) - 1)
(Controls are named with a single letter followed by sequential numbers.)

How can I refer to the corresponding variable from within this loop?

For example when the control loops through control G10, I'd like to refer to C10.

I'm having trouble building the variable reference:
I know this would be possible by creating another variable to refer to a string created by concatenating C and the Number like this:

Code:
Dim CandNumber As String
CandNumber = "C" & Right(controlname, Len(controlname) - 1)
'This will build the control name, but how can I reference its contents?

I would like to skip this silliness completely and do it the right way - how is this accomplished? I trust you can understand what I'm trying to get at.. I just don't exactly know how to describe it clearly.
 
Code:
dim C(12) as string 

msgbox = C(Right(controlname, Len(controlname) - 1))


You could stick the number in an integer variable first if you want to.
Code:
 dim i as integer
 dim C(12) as string 

i = Right(ControlName, Len(ControlName) - 1)
msgbox c(i)
 
Last edited:
dim c(12) actually gives you a 13 element array from 0 to 12 so the subtraction of the number of your control might not be necessary
 
This is actually exactly what I've been doing and
Code:
MsgBox C(1)
Shows a blank message box.

C1 is declared and contains a value.

However
Code:
MsgBox C1
Works fine.
 
Code:
Dim C(12) As String
C0 = "0"
C1 = "1"
C2 = "2"
MsgBox C(1)

This returns a blank msgbox - try it??
 
it will do

c(1) <> C1

You're not using option explicit so VBA is creating those variables on the fly and your data is now in a variant type Variable called C0 rather than in element 0 of the array c().

Add

"OPTION EXPLICIT" under Option Compare Database in your modules and run it again, see what happens.

To have it set by default go to Tools, options, editor and check the box require variable declaration in the VBA editor.
 
No, is that the problem? It's using Option Compare Database.
 
OK, that sounds good. Do I need to use parenthesis when setting the variable's value?

Like c(1) = "tblName.FieldName"
 
The problem is that without Option Explicit VBA is interpreting your typo as a need for new variables called C0, C1 etc etc

You meant to type
Code:
c(1) = "1"

msgbox c(1)

But you've typed:

Code:
c1 = "1"

msgbox c(1)

hence c(1) is empty because you've put the value in a new variable called C1 instead.

If you add option explicit when you try to run the code again you'll get a compile error with c0 highlighted and the message "Variable not declared", because it isnt.
 

Users who are viewing this thread

Back
Top Bottom