我怎样才能dynamic地添加YES或NOcheckbox到用户窗体?

我以下面的方式dynamic加载一个Useform。

Sub UserForm_Initialize() With Worksheets("SetupQuestions") Lrow = Worksheets("SetupQuestions").Cells(Rows.Count, 1).End(xlUp).Row Set rngSource = .Range("A2:B" & Lrow) End With NewrngSource = Replace(rngSource.Address, "$", "") With ListBox1 .Value = "None" .ColumnHeads = True .ColumnCount = 2 .ColumnWidths = "50;100" .RowSource = "SetupQuestions!" & NewrngSource & "" .MultiSelect = fmMultiSelectMulti .BoundColumn = 1 End With End Sub 

我试图找出一种方法来添加对应于列表框中的项目的CheckBoxes。 我可以很容易地从我的列表框中获取项目。

 Sub CommandButton1_Click() Dim text As String Dim i As Integer For i = 0 To Me.ListBox1.ListCount - 1 If Me.ListBox1.Selected(i) Then text = text & Me.ListBox1.List(i, 0) & ". " & Me.ListBox1.List(i, 1) & " " & Chr(10) End If Next i Sheets("NEW Format").Range("BB1").Value = text Unload Me End Sub 

我只是不知道如何dynamic添加CheckBoxes。 这里是我的Lisbox视图,还有一个CheckBox是YES / NO对象,但是我只有一个这里列出的,我真的想要所有与列表中每个项目对应的CheckBox。

在这里输入图像说明

我在网上看到一个看起来很有前途的示例脚本,但它在我的列表框中添加了CheckBox,而不是在右边。

 For Each rngCell In rngSource If rngCell.Value <> "" Then Set NewChkBx = Me.Controls.Add("Forms.CheckBox.1") With NewChkBx .Caption = rngCell.Value .Left = 5 .Top = TopPos .AutoSize = True If .Width > MaxWidth Then MaxWidth = .Width End With TopPos = TopPos + 15 End If Next rngCell 

我可以自动生成checkbox,但是这个过程耗时太长,而且我正忙着处理这个事情。 我最后添加了一些与列相邻的AND / OR字段,并添加了一些代码来正确处理所有内容。

在这里输入图像说明

现在全部设置。 感谢大家。

我正在给出一个答案,即使你不再需要它了。 其他人可能会寻找它。

以下是在用户窗体中创build2个checkbox的示例代码:

 Option Explicit 'inside userform's code Private Sub AddCheckboxes() Dim i& For i=1 to 2 with Me.controls.add("Forms.Checkbox.1","CheckBx" & i ,true) '3 arguments : the first is a fix one (do not mind the ".1" inside it, it is the way it needs to be ; the 2nd is the name of the control, the 3rd means visible=true .top=50 + (i-1)*20 'commencing at 50 and having a distance of 20 between controls .Left = 50 .Caption= "Autorize or Do something as #" & i 'for example end with next i end sub 

如果有很多控件,最好的办法就是把它们放在一个字典数组中,在我的例子中,我经常使用calsses字典(这个类有很多控件),像这样我可以为所有这些控件做一个共同的行为,例如_mousemove_mousedown