Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Control Method, finding control name

Status
Not open for further replies.

briancoats

Programmer
May 1, 2003
61
US
This is interesting,

If I were to wish to do a GotFocus methos this will work for any control.

Me.ActiveControl.BackColor = Yellow 'Yellow is Defined Constant

Now here is ther kicker. If I want to do a LostFocus method, is there a line of code that will work for all controls. Given:

Private Sub MyControl_LostFocus()
'is there a command that will tell me what control fired
'Off this Method so that I can use the same code in all
'LostFocus Methods
End Sub

Thanks you for your help (Though I am not convinced that there is an answer.)

Brian Coats
 
Try this:

Place 2 text boxes on a form, then add the following code:

Dim LastControl as String 'form-level global variable

Private Sub Text1_GotFocus()
LastControl = Me.ActiveControl.Name
Me.ActiveControl.BackColor = vbRed
End Sub

Private Sub Text1_LostFocus()
ChangeLastControlColor
End Sub

Private Sub Text2_GotFocus()
LastControl = Me.ActiveControl.Name
Me.ActiveControl.BackColor = vbRed
End Sub

Private Sub Text2_LostFocus()
ChangeLastControlColor
End Sub

Private Sub ChangeLastControlColor()
For Each Control In Me
If Control.Name = LastControl Then
Control.BackColor = vbGreen
End If
Next
End Sub


I used to rock and roll every night and party every day. Then it was every other day. Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson
 
I like that, I was hoping for a little less code but I like it.

Thanks.

Brian Coats
 
Well, if you dim LastControl as a control instead of a string, and use:

Set LastControl = Me.ActiveControl

Then your public sub turns into this:

Private Sub ChangeLastControlColor()
LastControl.BackColor = vbGreen
End Sub

But, unless you have a need for more code in the sub that does something else, you can just move the one line to your lostfocus event.

Less code!

Robert
 
OK, that is sort of what I was thinking about but I was not sure if you would have to dim the last control as say a textbox or combobox. I had thought that maybe control would be to generic for what I was wanting to do.

Thanks

Brian Coats
 
I just tried theVampires suggestion and it worked wonderfully. Thank you again.
 
No Problem.

Just thinking about it, it may be better for you to leave it in the public sub. That way, if you decide you don't like the color, you only have to change the code in one place.

Robert
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top