Ask the MultiValued Visual
Basic Expert - #16
(as published in Spectrum
magazine Sep/Oct 1999)
To email your questions to "Ask the MultiValued VB
Expert", click here.
Copyright © 1996-99 Caduceus Consulting. All rights reserved.

Setting Focus to a Variable Control
Hello:
I wonder if you can help. I am trying to set
focus to a control specified by the value of a string . However,
it is not proving to be as easy as it should be. When I am trying
to "Set" the name it either will not accept the value
as there is a Type mismatch or it won't accept the name we try to
assign to it because this is a read-only property. Are there any
work-arounds or cunning solutions ? Here is the code I was
trying:
Dim objvar As
Control
Set objvar = Text2.Text
objvar.SetFocus
Joe Aeberhard, U.K.
I like your question, Joe, because the answer
might help people to better grasp the concept of objects and
controls as variables. The above code results in a Type mismatch,
because it attempts to set a control variable (objvar) to a
string (Text2.Text). A variable dimensioned as
"Control" can only be Set to another control variable
or an existing control (by name), as in:
Set
objvar = Text2
You are also correct the Name property is
read-only, but you can still use that property by adding in the
concept of Control Collections. Right now you are attempting to
solve the problem by saying: "Set a variable to the
specified control and then set focus to it". Instead, think
of your problem in this way: "Find the control whose Name
property equals the specified string and then set focus to
it". To search through the controls on any given form, use
the following code:
Dim
objvar As Control
For Each objvar In Form1.Controls
. . If objvar.Name = Text2.Text
Then
. . .
. objvar.SetFocus
. . .
. Exit For
. . End If
Next objvar
The "For Each" clause steps through
all the members of a collection, in this case all of the controls
on Form1. The variable (objvar) is dimensioned to be the same
type as each member of the collection, in this case as
"Control". The above code will accomplish your desired
funtionality.

To email your questions to "Ask the MultiValued VB
Expert", click here.
Copyright © 1996-99 Caduceus Consulting. All rights reserved.
Added: August 18, 1999.
Return to Caduceus
Consulting Home Page