从控件数组中单击的按钮获取按钮属性

问题描述 投票:1回答:2

我需要帮助如何从控制阵列中的单击按钮获取按钮比例。我在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。

vba word-vba
2个回答
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)

2
投票

引用CommandButtonEvents是您在UserForm_Initialize中设置的MSForms.CommandButton。

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

重命名Class 1 - > CommandButton Events和CommandButton Events - > Button,对我来说更有意义。

© www.soinside.com 2019 - 2024. All rights reserved.