首页 > 解决方案 > 将一个类模块子分配给多个 OptionButtons vba

问题描述

我正在 Microsoft Word 中的表单上动态创建选项按钮。我通过下面的代码以编程方式为新选项按钮分配了一个子按钮,但我无法弄清楚如何将一个类分配给多个按钮。这可能吗?

下面的代码有效,但它只在最后一个按钮上抛出消息框。我认为我的代码正在做的是每次将此类重新分配给最新的按钮,而不是在有意义的情况下向该类添加按钮?这么多按钮调用 Focus_btn_Click 事件,我该如何做呢?

我的班级(称为“clsSectorbtn”):

Public WithEvents Focus_btn As MSForms.OptionButton
Sub Focus_btn_Click()
    Msgbox "Test"
End Sub

我的表格中的代码:

Dim SectorBtn As New clsSectorBtn    
Sub Create_Radios(Radio_Array)
    Dim RadioArray (0 to 2) As String
    RadioArray(0) = "optionbutton1"
    RadioArray(1) = "optionbutton2"
    RadioArray(2) = "optionbutton3"
    Set Fm = UserForm1("Frame1")

    For x = 0 To UBound(Radio_Array)
        Set opt = Fm.Object.Controls.Add("Forms.OptionButton.1")
        opt.Caption = Radio_Array(x)
        Set SectorBtn.Focus_btn = opt
    Next x
End Sub

标签: vbams-word

解决方案


您需要一个全局集合来保存 的实例clsSectorbtn,并且使用“工厂”函数来构建每个实例更容易。

我会做这样的事情:

Dim colBtn As Collection    

Sub Create_Radios(Radio_Array)
    Dim RadioArray (0 to 2) As String
    RadioArray(0) = "optionbutton1"
    RadioArray(1) = "optionbutton2"
    RadioArray(2) = "optionbutton3"
    Set Fm = UserForm1("Frame1")

    Set colBtn = New collection
    For x = 0 To UBound(Radio_Array)
        Set opt = Fm.Object.Controls.Add("Forms.OptionButton.1")
        opt.Caption = Radio_Array(x)
        colBtn.Add OptObject(opt)
    Next x
End Sub

'create an instance of clsSectorbtn and assign an option button to it
Function OptObject(opt) As clsSectorbtn
    Dim rv as New clsSectorbtn
    Set rv.Focus_btn = opt
    Set OptObject = rv
End Function

推荐阅读