在运行时添加事件

时间:2015-09-18 07:03:24

标签: excel vba excel-vba events

我在VBA中创建了一个元素列表,每个循环都有一个这样的元素:

Dim WithEvents olblCount As MSForms.Label
Dim WithEvents otxtGet As MSForms.TextBox
Dim WithEvents ospinGet As MSForms.SpinButton

Private Sub UserForm_Layout()
    i = 0
    For Each C In Range("Anzahl")
        If C = "" Then
            Exit For
        End If
        Set olblCount = Controls.Add("Forms.Label.1", "lblCount" + CStr(i), True)
        With olblCount
            .Font.Size = 12
            .Left = 110
            .Top = 12 + i * 24
            .Height = 18
            .Width = 30
            .TextAlign = fmTextAlignRight
            .SpecialEffect = fmSpecialEffectBump
            .Caption = C
        End With

        Set otxtGet = Controls.Add("Forms.TextBox.1", "txtGet" + CStr(i), True)
        With otxtGet
            .Font.Size = 12
            .Left = 155
            .Top = 12 + i * 24
            .Height = 18
            .Width = 35
            .TextAlign = fmTextAlignRight
            .Text = 1
        End With

        Set ospinGet = Controls.Add("Forms.SpinButton.1", "spinGet" + CStr(i), True)
        With ospinGet
            .Left = 188
            .Top = 12 + i * 24 - 1
            .Height = 18
            .Width = 12
            .Value = 1
        End With
        i = i + 1
    Next
End Sub

现在我需要为每个spinButton创建一个EventHandler,并在其前面使用txt获取连接。

当我手动创建spinButtons时,它将是这样的:

Private Sub SpinGet_Change()
    txtGet1.Value = SpinButton1.Value
    SpinButton1.Max = txtCount.Caption
    SpinButton1.Min = 1
End Sub

但是如何在脚本中为每个spinButton创建它们?

1 个答案:

答案 0 :(得分:0)

使用相同的逻辑,因为您使用WithEvents关键字可以访问该对象的事件处理程序,例如:

Private Sub ospinGet_Change()
   '// Your code here...
End Sub

确保这些事件处理程序也在类模块中。