Indirection can be achieved
If this is what you want. To take you literally, the other
var is already defined, so you are not really trying to
create new variables during runtime which I think a few of
the ohter replies assume.
To use the contents of a string to determine which of
several variables to change, is easiest to do with a big
case statement. Of course, I assume you do not want this
because perhaps you want to set/get this value from many
places in your code.
Although I cannot see any possible reason why you would
absolutely need this (there are always alternatives), I
have put together a simple piece of demo code which does
the following:
1) User selects a variable name from a combo
box (names hard coded in the list for the demo but you can
easily make the list dynamic)
2) User enters an integer value in the text box
3) User hits the command button, and the appropriate var is
updated . This is achieved without the use of any testing
of the user selection.
To use this in your code, you would have to do as I have
done and give VB an alternative way to address the var you
are after.
This method is only one such way to do this.
Code:
Option Explicit
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" ( _
lpvDest As Any, lpvSource As Any, ByVal cbCopy As Long)
Dim AnotherVar As Integer
Dim AnotherVar2 As Integer
Dim sillyCol As Collection
Private Sub Command1_Click()
Debug.Print AnotherVar, AnotherVar2
' set whichever var is selected form the combo box
' to the contents of the text box.
On Error Resume Next
Dim val As Integer
val = CInt(Text1.Text)
' ignore conversion errors - leave as 0
If Err <> 0 Then Err.Clear
Dim myPointer As Long
myPointer = CLng(sillyCol(Combo1.Text))
If Err <> 0 Then
MsgBox "the variable selected cannot be found in the collection"
End
End If
CopyMemory ByVal myPointer, val, 2
Debug.Print AnotherVar, AnotherVar2
On Error GoTo 0
End Sub
Private Sub Form_Load()
Set sillyCol = New Collection
' some test integers
AnotherVar = -23
AnotherVar2 = 1023
' record the varname against it's pointer
sillyCol.Add Str(VarPtr(AnotherVar)), "AnotherVar"
sillyCol.Add Str(VarPtr(AnotherVar2)), "AnotherVar2"
End Sub
Test it out for yourself.
Cheers