VBA WithEvents无法正常工作

时间:2012-08-07 15:58:55

标签: vba events controls userform

我基本上创建了一个在运行时生成的项目列表。这些项目在用户表单上列为标签(这些项目存储在链接列表中)。对于每个项目,我想添加一个旋钮,以便我可以在列表中上下移动项目。我的旋钮创建得很好,我编码的事件不起作用?我不确定我做错了什么。可能简单......

这是用于保存事件的类模块:cls_Spin_Btn

Private WithEvents Spin_Events As SpinButton

Private Sub Spin_Events_SpinUp()

    Debug.Print "Hey. Spin button worked."

End Sub

Public Property Set SetNewSpinButtion(newSpinBtn As MSForms.SpinButton)

    Set Spin_Events = newSpinBtn

End Property

这是代码从模块调用:

Function AddRunToForm(f As UserForm, r As ProductionRun, top As Integer) As Integer

Dim Run_SpinBtn As MSForms.SpinButton
Dim spinBtn As cls_Spin_Btn

Set Run_SpinBtn = f.Controls.Add("Forms.SpinButton.1", r.ProdID & "_SBtn", True)
Set spinBtn = New cls_Spin_Btn

With Run_SpinBtn

    .top = ProdID_Lbl.top
    .Left = 5
    .height = 10
    .Width = 12
    .height = 18
    .Visible = True

End With

Set spinBtn.SetNewSpinButtion = Run_SpinBtn

AddRunToForm = ProdID_Lbl.top + ProdID_Lbl.height

End Function

此代码从同一模块中的循环调用,为每个项目创建标签和旋钮。我究竟做错了什么?非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

在您的用户表单代码模块中,输入此

Private mcolSpinButtons As Collection

Public Property Get SpinButtonCollection() As Collection

    If mcolSpinButtons Is Nothing Then Set mcolSpinButtons = New Collection

    Set SpinButtonCollection = mcolSpinButtons

End Property

只要您的用户窗体处于打开状态,这将允许您访问将保留在范围内的模块级变量。当您将cls_Spin_Btn实例放入该集合时,它们也将保留在范围内。

然后在您的函数中,创建新的旋转按钮类实例后,将其添加到集合

f.SpinButtonCollection.Add spinBtn, spinBtn.Name