如何使用vba在userform中声明自定义事件

Mic*_*ael 1 vba ms-word word-vba

我有userform收集一些用户输入.现在我要做的是,当单击"确定"按钮时,声明从userform抛出一些事件.我是vba的新手,所以我不知道怎么做.任何代码或指向教程的链接将不胜感激.

Load UserForm1
UserForm1.Show
//here I want to capture UserForm1 OK button's click event and read the data
Run Code Online (Sandbox Code Playgroud)

dee*_*dee 7

  • 在子形式声明事件中并在某个时刻提升它:

公共事件 clickOnChild(ByVal inputText As String)

RaiseEvent clickOnChild(Me.TextBox1.Value)

  • 在自定义类模块,工作表类模块或其他用户表单中,您可以捕获该事件.但是,您无法在标准模块中捕获事件,因为WithEvents变量仅在对象模块中有效.要在例如其他用户表单中捕获事件,请声明类型为childUserForm的WithEvents变量,并添加事件处理程序,其中将捕获和处理事件:

Private WithEvents childForm作为childUserForm

Private Sub childForm_clickOnChild(ByVal inputText As String)


完整的例子:

儿童用户表格:

Option Explicit

Public Event clickOnChild(ByVal inputText As String)

Private Sub CommandButton1_Click()
  RaiseEvent clickOnChild(Me.TextBox1.Value)
End Sub
Run Code Online (Sandbox Code Playgroud)

父用户表单:

Option Explicit

Private WithEvents childForm As childUserForm

Private Sub CommandButton1_Click()
  childForm.Show
End Sub

Private Sub childForm_clickOnChild(ByVal inputText As String)
  MsgBox "Input in child form was: " & inputText
End Sub

Private Sub UserForm_Initialize()
  Set childForm = New childUserForm
End Sub
Run Code Online (Sandbox Code Playgroud)