vba - 将一个类模块子分配给多个 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
解决方案
您需要一个全局集合来保存 的实例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
推荐阅读
- azure-devops - API POST 不适用于带有 Azure DevOps Server 的分支(2019 更新 1)
- python - Pygame AI 无人机
- google-analytics - gtag 综合浏览量的“page_location”报告在哪里?
- spring-boot - 带有 JDBC 身份验证的 Spring Security 5:UserDetailsService bean 仍然在内存中,而不是 JDBC
- algorithm - 在有向图中找到长度可被 3 整除的从 s 到 t 的步行
- python - 在python中按日期和ID计算值的变化
- regex - 如何从:(冒号)分隔值中提取特定列?
- python - AWS Lambda [错误] 函数采用 1 个位置参数,但给出了 2 个
- python - 创建数据库时烧瓶 sqlalchemy 和 mysql 错误
- html - 有没有办法在 react-static 中添加图标?