excel - Trigger Enter field behaviour through class for a control
问题描述
I raised a query which now works as per David Zemens' instructions and BrakNicku guidance.
Problem is one of the events I want to use is Enter. Within the class, I don't get the option for this event. Is there is a way to add this to the class or trigger an Enter event for the control somehow?
I tried most of the events available within the class but none of them behave the way I need them to.
A quick background: I use Enter event to set help text for the field in focus. So every time a user enters a field, I have a help textbox that gets populated with help text.
I am unable to share the workbook.
解决方案
Let's say your userform (Userform1) looks like this
I am going to demonstrate the Enter Event
for 2 controls. TextBox
and ComboBox
.
Ensure that you place the CommandButton1
first on the userform. Or alternatively, set it's TabIndex
to 0
. This is so that the command button takes focus first when the userform loads and you can test the Entering
of TextBox
and ComboBox
.
Paste this in a class module. My Class module name is Class1
Option Explicit
Public WithEvents Usrfrm As UserForm1
Const MyMsg As String = "Hiya there. Did you just try to sneak into the "
Private Sub Usrfrm_OnEnter(ctrl As msforms.Control)
Select Case True
Case TypeName(ctrl) Like "ComboBox"
'Call Usrfrm.Combobox_List(ctrl)
MsgBox MyMsg & "combobox?", vbCritical, "Aha!"
Case TypeName(ctrl) Like "TextBox"
MsgBox MyMsg & "textbox?", vbCritical, "Aha!"
End Select
End Sub
Paste this in the userform code area
Option Explicit
Public Event OnEnter(ctrl As msforms.Control)
Private prevCtl As msforms.Control
Private mycls As Class1
Private IsfrmUnloaded As Boolean
Private Sub CommandButton1_Click()
Unload Me
End Sub
Private Sub UserForm_Layout()
Call spyWhatsGoingOn
End Sub
Private Sub spyWhatsGoingOn()
Set mycls = New Class1
Set mycls.Usrfrm = Me
IsfrmUnloaded = False
Set prevCtl = Me.ActiveControl
RaiseEvent OnEnter(Me.ActiveControl)
Do While IsfrmUnloaded = False
If Not prevCtl Is Nothing Then
If Not prevCtl Is Me.ActiveControl Then
RaiseEvent OnEnter(Me.ActiveControl)
Me.ActiveControl.SetFocus
End If
End If
Set prevCtl = Me.ActiveControl
DoEvents
Loop
End Sub
Demo
推荐阅读
- ruby-on-rails - NameError: uninitialized constant 和 LoadError: Unable to autoload constant
- python - 在python字典中的for循环中添加相同的键和值
- c# - 我可以从导致 WPF 中代码的属性更改的触发器中识别出哪个路由事件吗?
- amazon-web-services - AWS ECR:上传 docker 图像给出以下错误
- angular - Angular - 如何将参数传递给 TypeScript 基类
- spring - 如何处理 org.apache.tomcat.util.http.fileupload.impl.InvalidContentTypeException
- swift - Docker + Swift + 传递参数
- python - 如何在 Python 中将所有特殊字符作为列表获取?
- javascript - Javascript 天数 getElementbyID 问题
- python-3.x - 使用 lambda 函数调整图像大小并将其从一个 s3 移动到另一个 s3