动态添加复选框到表单vba上的框架

时间:2016-12-06 17:24:31

标签: vba excel-vba excel

如何在userForm框架中添加多个复选框?这似乎是一件微不足道的事情,但我的代码只为数组中的最后一项生成一个复选框。

Private Sub btnGenerate_Click()
Dim i As Long
Dim lic As licence
Dim temp As Variant
Dim desc As String
Dim chkbox As MSForms.CheckBox
Dim str As String

For Each lic In licenceCollection
    temp = lic.getClause
Next lic

For i = LBound(temp) To UBound(temp)
    'Debug.Print temp(i)
    desc = "Future-Sampling " & i
    'Utility.createCheckBoxes temp(i), desc
    Set chkbox = licenceForm.resultFrame.Controls.Add("Forms.Checkbox.1", desc)
    chkbox.Caption = temp(i)
    chkbox.Value = desc
    chkbox.Width = "450"
    chkbox.Height = "50"
    chkbox.WordWrap = True
    chkbox.Value = False
    chkbox.GroupName = "Future Sampling"
Next
End Sub  

这里的任何建议都非常感谢。提前致谢。

3 个答案:

答案 0 :(得分:1)

它们都被创建得很好,但是你只能看到最后一个的原因是它们在添加时都在默认位置叠加在一起。您需要使用.Top.Left属性定位它们:

Dim xPos As Long
For i = LBound(temp) To UBound(temp)
    desc = "Future-Sampling " & i
    Set chkbox = Me.Controls.Add("Forms.Checkbox.1", desc)
    With chkbox
        .Top = xPos
        .Caption = temp(i)
        .Value = desc
        .Width = 450
        .Height = 24
        .WordWrap = True
        .Value = False
        .GroupName = "Future Sampling"
        xPos = xPos + 24
    End With
Next

答案 1 :(得分:0)

我认为问题是,你在相同位置添加组件,因此它是重叠的,你只看到最后一个,不是吗?如果我没记错的话,您需要调整lefttop坐标。

答案 2 :(得分:0)

谢谢大家,这似乎可以解决问题!我从没想过这个续集

下面修改了代码段,

      For i = LBound(temp) To UBound(temp)
                desc = "Future-Sampling " & i
                Set chkbox = Me.resultFrame.Controls.Add("Forms.Checkbox.1", desc)
                With chkbox
                    .Top = xPos
                    .Caption = temp(i)
                    .Value = desc
                    .Width = 450
                    .Height = 24
                    .WordWrap = True
                    .Value = False
                    .GroupName = "Future Sampling"
                    xPos = xPos + 24
                End With


        Next i