如何向UserForm动态添加YES或NO CheckBoxes?

时间:2017-01-09 16:00:17

标签: excel vba excel-vba

我正在以下列方式动态加载一个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

我正在试图找出一种方法来添加与ListBox中的项目对应的CheckBoxes。我可以轻松地从ListBox中获取项目。

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

我无法弄清楚如何动态添加CheckBoxes。这是我的Lisbox的视图,以及一个用于YES / NO对象的CheckBox,但我在这里只列出了一个,我真的希望所有CheckBox都对应于列表中的每个项目。

enter image description here

我在网上看到一个看起来很有前途的示例脚本,但它在我的ListBox下面添加了CheckBoxes,而不是在它的右边。

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

2 个答案:

答案 0 :(得分:0)

我可以自动生成CheckBoxes,但这花费的时间太长而且我正在为我正在处理的事情耗尽时间。我最后添加了列中相邻列的一些AND / OR字段,并添加了一些代码来正确处理所有内容。

enter image description here

现在全部设定。 谢谢大家。

答案 1 :(得分:0)

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

以下是在userform中创建2个复选框的示例代码:

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 ...