answerSeeker
answerSeeker

Reputation: 2772

How do I get the textbox name after it's focused or clicked in vba

How can I get the name of the current textbox (activex control)that is focused or clicked on in VBA? Note this textbox is on a worksheet and not a form.

Upvotes: 0

Views: 990

Answers (1)

Toddleson
Toddleson

Reputation: 4457

Try something like this:

Dim ActiveShape As Object

Private Sub TextBox1_GotFocus()
    Set ActiveShape = Me.TextBox1
End Sub

Private Sub TextBox2_GotFocus()
    Set ActiveShape = Me.TextBox2
End Sub

Sub Test()
    MsgBox "You are currently on, or have recently clicked on " & ActiveShape.Name
End Sub

I put ActiveShape as a Module-Level variable, this will save it between executions. Then for each of your textboxes, put a script in their _GotFocus event. This script will save the most recently interacted textbox onto the ActiveShape variable.

If you want to, you can put a script into each textboxes _LostFocus event to set ActiveShape to Nothing. This will ensure ActiveShape is only the currently active shape and not the most recently active shape, if you care about that distinction.

Upvotes: 1

Related Questions