How to create a variable name from a string

I need to create a variable or control name from a string.

For example, I am given a number which is 1, 2, 3, 4 or 5.  

If the number is 1, I need to reference the form control named cboWS1.
If the number is 4, I need to reference the from control named cboWS4.
etc.

I could use the Select Case statement for this simple example, but my application utilizes a dozen variables that need to have the selected number included in their names...
cboWS4
cboAG4
cboLT4
etc.

It's simple enough to concatenate the "1" to "cboWS" to create "cboWS1", but how do I use this string to create a statement such as...       Variable1 = cboWS1

Something to the effect...      Variable1 = CName("cboWS1")
David_W_RAsked:
Who is Participating?
 
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
"If the number is 1, I need to reference the form control named cboWS1."

You can pass the name to the controls collection to get a reference to the control:
Private Sub Command1_Click()
    Dim number As Integer
    number = 1
    
    Dim ctlName As String
    ctlName = "cboWS" & number
    
    Dim cb As ComboBox
    Set cb = Me.Controls(ctlName)
    ' ... do something with "cb" ....
    MsgBox ctlName & " --> " & cb.Value
End Sub

Open in new window

0
 
David_W_RAuthor Commented:
This does the job.  Thanks for the insight.  Got my mind out of the idle state.  Was it any challenge for yours?
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
I haven't used MS Access in literally about a decade.  Had to open up Access 2010 and play with it to make sure I was right.  ;)
0
All Courses

From novice to tech pro — start learning today.