1

我正在按照这个 MSDN 指南创建自定义事件。我觉得我现在理解了这个过程,但我不知道为什么我会得到一个Compile Error: Event Not Foundfor RaiseEvent ItemAdded。奇怪的是,IDE 可以识别 ItemAdded 事件(我可以全部输入小写,然后自动正确格式化),所以我知道它可以被 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。

用户表单代码:

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
4

1 回答 1

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)
于 2013-03-15T01:02:45.380 回答