VBA – 编程类操作用户窗体上的所有checkbox时出错

这里是我想要做的一些背景:我创build一个用户窗体跟踪库存项目和价格,使用多页对象中的checkbox。 店员检查一切顺序,并使用提交button,这将采取一些行动。

为了让项目在库存项目每次更改时都不需要编码人员,当激活用户窗体时,checkbox将从库存工作表上的单元格值dynamic生成。 店员只是调整库存表,表单会自动调整。

这是我的代码来dynamic创build所有的checkbox(目前这种forms可以容纳多达160个可能的checkbox),以防万一这是我的问题(注意,多页上的每个选项卡上有一个框架,所有checkbox都在框架,所以我可以改变背景颜色,这个例子中的框架被命名为“frmreg”):

Sub StoreFrmRegCheckboxGenerator() 'Works with the store userform Dim curColumn As Long Dim LastRow As Long Dim i As Long Dim chkBox As msforms.CheckBox 'This sub dynamically creates checkboxes on the Regular Items tab based 'on values in Column A of the Inventory sheet curColumn = 1 'Set your column index here LastRow = Worksheets("Inventory").Cells(Rows.Count, curColumn).End(xlUp).Row For i = 2 To 9 If Worksheets("Inventory").Cells(i, curColumn).Value <> "" Then Set chkBox = store.frmreg.Controls.Add("Forms.CheckBox.1", "CheckBox_" & i) chkBox.Caption = Worksheets("Inventory").Cells(i, curColumn).Value & " - $" & Worksheets("Inventory").Cells(i, curColumn).Offset(0, 1).Value chkBox.AutoSize = True chkBox.WordWrap = True chkBox.Left = 5 chkBox.Top = 1 + ((i - 1) * 25) End If Next i 'Cut some code out here identical to this previous section, but for the rest of the cells in column A up to Row 33, in blocks of 8 End Sub 

上面的代码在Userform_Initialize子部分,并且完美地工作。

但是,由于checkbox的数量不是静态的,可以多达160个,所以我试图编写一个子任务,在任何时候点击相同的操作。

我发现最接近的解决scheme是从这个问题: Excelmacros用户窗体 – 单一代码处理多个checkbox ,从Sous2817。

这是他正在尝试使用的代码:

在一个新的类模块中:

  Option Explicit Public WithEvents aCheckBox As msforms.CheckBox Private Sub aCheckBox_Click() MsgBox aCheckBox.Name & " was clicked" & vbCrLf & vbCrLf & _ "Its Checked State is currently " & aCheckBox.Value, vbInformation + vbOKOnly, _ "Check Box # & State" End Sub 

“存储”用户窗体,在右上方Option Option:

  Dim myCheckBoxes() As clsUFCheckBox 

在Userform_Initialize子的底部,在我调用所有dynamic创build所有checkbox的子集之后:

 Dim ctl As Object, pointer As Long ReDim myCheckBoxes(1 To Me.Controls.Count) For Each ctl In Me.Controls If TypeName(ctl) = "CheckBox" Then pointer = pointer + 1 Set myCheckBoxes(pointer) = New clsUFCheckBox Set myCheckBoxes(pointer).aCheckBox = ctl End If Next ctl ReDim Preserve myCheckBoxes(1 To pointer) 

当我尝试打开用户表单时,出现以下错误:

“编译错误:用户定义types未定义”

指向这一行:

 Dim myCheckBoxes() As clsUFCheckBox 

我是否缺less库引用? 我一直无法弄清楚这一点。