我有收集一些用户输入的用户表单。现在我正在尝试做的是在单击“确定”按钮时声明一些要从用户窗体中抛出的事件。我是 vba 新手,所以我不知道该怎么做。任何代码或教程链接将不胜感激。
Load UserForm1
UserForm1.Show
//here I want to capture UserForm1 OK button's click event and read the data
Public Event clickOnChild(ByVal inputText As String)
RaiseEvent clickOnChild(Me.TextBox1.Value)
Private WithEvents childForm As childUserForm
Private Sub childForm_clickOnChild(ByVal inputText As String)
Complete example:
Child user form:
Option Explicit
Public Event clickOnChild(ByVal inputText As String)
Private Sub CommandButton1_Click()
RaiseEvent clickOnChild(Me.TextBox1.Value)
End Sub
Parent user form:
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
正如我在评论中所说,我认为您想要做的事情是不可能的,但我想到了以下解决方法:
如果您的用户输入非常简单,例如只输入一个字符串,则消息框可以工作:
Dim sUserInput As Variant
sUserInput = InputBox("Please enter something useful.", "Title", "Default")
Debug.Print "sUserInput=" & sUserInput
如果您需要表单来捕获用户输入,则将其设为模态然后通过公共方法公开一个值可能会起作用。
在表格中:
Option Explicit
Private msFormString As String
Private Sub CommandButton1_Click()
msFormString = "Someone clicked on Button 1!"
'***** Note: if you use Unload Me, the string
'***** is unloaded with the form...
Me.Hide
End Sub
Public Function GetFormString() As String
GetFormString = msFormString
End Function
调用代码:
Load UserForm1
Call UserForm1.Show(vbModal)
Debug.Print "Value from UserForm1: " & UserForm1.GetFormString
注意:如果您需要传回更多数据,该函数可以返回一个对象、类或数组。