1

我有收集一些用户输入的用户表单。现在我正在尝试做的是在单击“确定”按钮时声明一些要从用户窗体中抛出的事件。我是 vba 新手,所以我不知道该怎么做。任何代码或教程链接将不胜感激。

Load UserForm1
UserForm1.Show
//here I want to capture UserForm1 OK button's click event and read the data
4

2 回答 2

7
  • 在子表单中声明事件并在特定时刻引发它:

Public Event clickOnChild(ByVal inputText As String)

RaiseEvent clickOnChild(Me.TextBox1.Value)

  • In a custom class module, worksheet class module or other user form you can catch the event. However you can't catch event in standard module because WithEvents variable are valid in object module only. To catch your event in e.g. other user form declare WithEvents variable of type childUserForm and add event-handler where the event will be catched and handled:

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
于 2012-10-22T12:17:50.700 回答
0

正如我在评论中所说,我认为您想要做的事情是不可能的,但我想到了以下解决方法:

  1. 如果您的用户输入非常简单,例如只输入一个字符串,则消息框可以工作:

    Dim sUserInput As Variant
    
    sUserInput = InputBox("Please enter something useful.", "Title", "Default")
    
    Debug.Print "sUserInput=" & sUserInput
    
  2. 如果您需要表单来捕获用户输入,则将其设为模态然后通过公共方法公开一个值可能会起作用。

    在表格中:

    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
    

    注意:如果您需要传回更多数据,该函数可以返回一个对象、类或数组。

于 2012-10-22T11:41:34.363 回答