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

家住魔仙堡 提交于 2019-12-24 11:37:47

问题


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.


回答1:


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).

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

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.



来源:https://stackoverflow.com/questions/57948670/in-a-vba-userform-which-event-is-triggered-when-exiting-a-filed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!