单击类模块中未触发的事件

时间:2017-10-16 19:40:35

标签: excel vba excel-vba class events

我有一个用户表单,显示逐行验证错误(在文本框中),我希望补充用户表单标签作为超链接,用户可以点击这些超链接直接转到有问题的单元格。

我有代码可以动态构建标签,并通过类模块添加了一个click事件,但是我无法在类模块中获取它来触发。

我确实修改了这段代码来构建这种类型的标签和动态点击事件,但是该代码在userform启动时加载标签并将每个类对象放入一个集合中。我不知道是否有必要构建我的解决方案,但我玩它并且无法使其工作。

如果需要,这是我在userform上放置标签的过程。如果需要验证,它将在另一个过程中运行。如果需要验证,则会显示Userform,并填充消息(以及此时创建的一个标签)。

Sub PlaceLinkLabel(SayWhat As String, WhichSheet As String, WhichRange As String)

    Dim lblNew As MSForms.Label
    Set lblNew = frmValidationMessage.Controls.Add(bstrProgID:="Forms.Label.1", Name:=SayWhat, Visible:=True)

    With lblNew
        With .Font
            .Size = 10
            .Name = "Comic Sans MS"
        End With

        .Caption = SayWhat
        .Top = 55
        .Height = 15
        .Left = 465
        .Width = 100
    End With

    Dim clsLabel As UserFormLabelLinks
    Set clsLabel = New UserFormLabelLinks
    Set clsLabel.lbl = lblNew

    With clsLabel
        .WhichRange = WhichRange
        .WhichSheet = WhichSheet
    End With

    'not sure if this is needed or not
    'Dim pLabels As Collection
    'Set pLabels = New Collection
    'pLabels.Add clsLabel

End Sub

这是UserFormLabelLinks课程模块:

Option Explicit

Private WithEvents pLabel As MSForms.Label
Private sWhichRange As String
Private sWhichSheet As String

Public Property Set lbl(value As MSForms.Label)
    Set pLabel = value
End Property

Public Property Get WhichSheet() As String
    WhichSheet = sWhichSheet
End Property

Public Property Let WhichSheet(value As String)
    sWhichSheet = value
End Property

Public Property Get WhichRange() As String
    WhichRange = sWhichRange
End Property

Public Property Let WhichRange(value As String)
    sWhichRange = value
End Property


Private Sub pLabel_Click()

    MsgBox "hi" 'when i click label, this does not fire

    'Application.Goto ThisWorkbook.Worksheets(WhichSheet).Range(WhichRange), True
    'ActiveWorkbook.FollowHyperlink ("#" & WhichSheet & "!" & WhichRange)

End Sub

2 个答案:

答案 0 :(得分:2)

MSForms.Label对象在PlaceLinkLabel退出后立即超出范围,UserFormLabelLinks对象引用也是如此;因此,您正在创建一个标签,但它是一个即发即弃的东西,一旦到达End Sub就无法以编程方式访问,因此事件永远不会触发。

您需要一个私有字段来保留UserFormLabelLinks对象引用(从而通过封装的MSForms.Label字段保留pLabel引用):

Option Explicit
Private clsLabel As UserFormLabelLinks

然后在程序中删除此行:

Dim clsLabel As UserFormLabelLinks

换句话说,将该局部变量提升为一个字段,以便在该过程完成后将其保留。

答案 1 :(得分:2)

另一种有效的方法:

配售 Private pLabels As Collection位于存储PlaceLinkLabel的模块顶部

并使用

If pLabels Is Nothing Then Set pLabels = New Collection
pLabels.Add clsLabel

PlaceLinkLabel模块

的末尾