我有userform收集一些用户输入。现在我要做的是,当单击“确定”按钮时,声明从userform抛出一些事件。我是vba的新手,所以我不知道怎么做。任何代码或指向教程的链接都将非常感激。
Load UserForm1
UserForm1.Show
//here I want to capture UserForm1 OK button's click event and read the data
答案 0 :(得分:7)
公开事件 clickOnChild(ByVal inputText As String)
RaiseEvent clickOnChild(Me.TextBox1.Value)
私有 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
父用户表单:
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
答案 1 :(得分:0)
正如我在评论中所说,我不认为你想做什么是可能的,但我想到了以下的解决方法:
如果您的用户输入非常简单,例如只输入一个字符串,就可以使用消息框:
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
注意:如果需要传回更多数据,该函数可以返回一个对象,类或数组。