Add event listener to Excel Textbox (lose focus)

16,538

For embedded ActiveX Excel control - add the following in the sheet mobile in VBA. TextBox1 is the name of the control:

Private Sub TextBox1_LostFocus()


End Sub

For userform - use the following where Textbox1 is the name of your textbox:

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)


End Sub

You can set the Cancel bool to True if you do not want to lose focus from the textbox. In addition the code is placed within the UserForm >> Right Click >> View Code.

Share:
16,538
Ole Henrik Skogstrøm
Author by

Ole Henrik Skogstrøm

Updated on June 05, 2022

Comments

  • Ole Henrik Skogstrøm
    Ole Henrik Skogstrøm almost 2 years

    I need to fire an sub or a command when a user is done using a text box in Excel.

    I have tried using the AfterUpdate() event and the LoseFocus() event like this:

    Public Sub Kommentar_AfterUpdate()
    
    MsgBox ("Hurray")
    
    End Sub
    

    The text box is named Kommentar and is inside the sheet Radio. Also, where is the code supposed to be written? i have tried placing it in code sheet for the Radio sheet, and in a separate module.

    Any tip, hint or answer is appreciated!

  • Ole Henrik Skogstrøm
    Ole Henrik Skogstrøm over 11 years
    This is a text box in excel, not inside a userform. Is this code meant for a userform text box?
  • InContext
    InContext over 11 years
    updated my answer and included embedded Excel controls. In VBA you can see in the event dropdown (top right) all available events for the control.
  • Davesexcel
    Davesexcel over 8 years
    How is this the answer, the textbox is not an activeX control.
  • InContext
    InContext over 8 years
    user added as an ActiveX control, this way you are not restricted to just the click event. For the avoidance of doubt I have updated my answer.