从控件数组

时间:2018-01-02 14:23:23

标签: vba word-vba

我需要帮助如何从控制阵列中的单击按钮获取按钮比例。我在userform中动态创建了许多按钮。点击按钮时,我需要从该按钮获取标题。

像这样......

Dim buttonsArray() As New Class1
Private Sub UserForm_Initialize()
    Dim objButton As MSForms.CommandButton
    Dim buttonY As Long
    buttonY = 30
    For i = 1 To 10
        Set objButton = myForm.Controls.Add("Forms.CommandButton.1", "btnNumber" & i)
        With objButton
            .Caption = "Button number " & i
            .Top = buttonY
            .Left = 10
        End With
        ReDim Preserve buttonsArray(1 To i)
        Set buttonsArray(i).CommandButtonEvents = objButton
        buttonY = buttonY + 30
    Next i
End Sub

在我的班级模块中......

Private Sub CommandButtonEvents_Click()
    MsgBox ("I'm here")
    MsgBox ("Button caption is " & ClickedButton.Caption)
End Sub

第一个msgbox可以工作,但第二个只是show for show。

2 个答案:

答案 0 :(得分:2)

参考 CommandButtonEvents 是您在UserForm_Initialize中设置的 MSForms.CommandButton

Private Sub CommandButtonEvents_Click()
    MsgBox ("I'm here")
    MsgBox ("Button caption is " & CommandButtonEvents.Caption)
End Sub

重命名 Class1 - > CommandButtonEvents CommandButtonEvents - > 按钮,对我来说更有意义。

答案 1 :(得分:2)

您的 Class1 代码应为:

Public WithEvents CommandButtonEvents As MSForms.CommandButton

Private Sub CommandButtonEvents_Click()
    MsgBox "I'm here"
    MsgBox "Button caption is " & CommandButtonEvents.Caption 
End Sub

在您的 UserForm_Initialize 代码中,更改:

Set objButton = myForm.Controls.Add("Forms.CommandButton.1", "btnNumber" & i)

为:

Set objButton = Me.Controls.Add("Forms.CommandButton.1", "btnNumber" & i)