user3138025
user3138025

Reputation: 825

In a VBA Userform, which event is triggered when exiting a filed

I'm using Microsoft Office Professional Plus (64 bit) on a Windows 10 (64 bit) platform. I have a subroutine that is processed when I make a change to a Userform field called MyDate. It's called Private Sub MyDate_AfterUpdate(). It's the second field on a form. It works fine as long as the contents of the MyDate field are edited. However, if the user doesn't need to update the contents of the MyDate field because they accept the default of the field and just presses the tab key past that second field, I'd still like the subroutine to be executed. What event can I use to activate code when I simply tab through the field and don't necessarily edit the contents? Thanks for looking at this.

Upvotes: 1

Views: 271

Answers (1)

Mathieu Guindon
Mathieu Guindon

Reputation: 71177

If you look at the top of the code panes, you'll notice two dropdowns. The left one contains all interfaces and event providers you can implement in that class (a UserForm is a class).

left dropdown listing (General), UserForm and TextBox1 items

Select your MyDate control from that dropdown; the right-side dropdown is now listing every event you could handle for this MyDate control:

right dropdown listing TextBox1 events

In this particular case, the Exit event seems a good candidate:

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    'make Cancel.Value = True to prevent exiting the control.
    '...ideally... make that conditional...
End Sub

By consistently using these dropdowns to let the VBE generate event handler procedures for you (instead of typing them up from memory), you avoid getting it wrong... and getting an event handler signature wrong can do anything from literally nothing at all, to compile errors if you're lucky, or weird and hard-to-diagnose behavior if you're less lucky.

Upvotes: 2

Related Questions