在UserForm中引发时找不到VBA自定义事件

时间:2013-03-15 00:46:36

标签: events vba userform

我正在关注this MSDN guide创建自定义事件。我觉得我现在理解了这个过程,但我无法弄清楚为什么Compile Error: Event Not Found获得了RaiseEvent ItemAdded。奇怪的是,ItemAdded事件被IDE识别(我可以全部小写输入,然后自动格式化),所以我知道它被VB识别。

DataComboBox类模块代码:

Public Event ItemAdded(sItem As String, fCancel As Boolean)

Private pComboBox As Control

Public Property Set oComboBox(cControl As Control)
    Set pComboBox = cControl
End Property

Public Property Get oComboBox() As Control
    oComboBox = pComboBox
End Property

Private Sub Class_Initialize()

End Sub

Private Sub Class_Terminate()

End Sub

UserForm包含两个控件 - 一个名为btnAdd的CommandButton和一个名为cboData的ComboBox。

UserForm代码:

Private WithEvents mdcbCombo As DataComboBox

Private Sub UserForm_Initialize()
    Set mdcbCombo = New DataComboBox
    Set mdcbCombo.oComboBox = Me.cboData
End Sub

Private Sub mdcbCombo_ItemAdded(sItem As String, fCancel As Boolean)
    Dim iItem As Long
    If LenB(sItem) = 0 Then
        fCancel = True
        Exit Sub
    End If
    For iItem = 1 To Me.cboData.ListCount
        If Me.cboData.List(iItem) = sItem Then
            fCancel = True
            Exit Sub
        End If
    Next iItem
End Sub

Private Sub btnAdd_Click()
    Dim sItem As String
    sItem = Me.cboData.Text
    AddDataItem sItem
End Sub

Private Sub AddDataItem(sItem As String)
    Dim fCancel As Boolean
    fCancel = False

    RaiseEvent ItemAdded(sItem, fCancel)

    If Not fCancel Then Me.cboData.AddItem (sItem)

End Sub

2 个答案:

答案 0 :(得分:2)

您无法在类文件级别之外引发事件。

在“DataComboBox1”中添加这样的例程,以允许您在外部引发事件。

Public Sub OnItemAdded(sItem As String, fCancel As Boolean)
    RaiseEvent ItemAdded(sItem, fCancel)
End Sub

然后使用当前对象调用OnItemAdded。

示例...

Private WithEvents mdcbCombo As DataComboBox
...
mdcbCombo.OnItemAdded(sItem, fCancel)

答案 1 :(得分:0)

我猜你想要做的是验证组合框输入,以便添加不空没有双重项。要实现此,您不需要任何自定义事件

Private Sub btnAdd_Click()
    Dim sItem As String
    sItem = Me.cboData.Text
    AddDataItem sItem, Me.cboData
End Sub

Private Sub AddDataItem(sItem As String, ByRef combo As ComboBox)

    If LenB(sItem) = 0 Then Exit Sub

    Dim iItem As Long
    For iItem = 0 To combo.ListCount - 1
        If combo.List(iItem) = sItem Then Exit Sub
    Next iItem

    combo.AddItem sItem

End Sub