Excel VBA将项添加到动态创建的ComboBox

时间:2016-08-19 15:38:27

标签: excel-vba for-loop collections combobox vba

我在我的用户表单中动态创建组合框,我想在表单上的每个组合框中添加相同的项目。

我创建了一个项集合(从和DB的sql语句中查询)。然后在我创建了组合框对象之后,我在集合中的每个项目中执行了for each语句以添加到组合框中,但组合框不会填充!控件已创建,但组合框为空

我检查了收藏品,看看我是否得到了价值观。 (请参阅我查询收集计数的行),我得到20个正确的项目。

我做错了什么?

编辑 - 我最近在我的父For For循环结束时添加了代码来调用以显示表单。这可能是表格没有正确显示的原因......

 Private Sub setVvalues(ByVal myCol as Collection)
    Dim xSel as Object, selName as String
    Dim sItem as Variant, selectItems as Collection, x as Variant
    Dim con as New ADODB.Connection
    Dim rs as New ADODB.Recordset

    ........[code that already works].........

    con.Open connectionStr   '<-- public String declared elsewhere


    Set selectItems = New Collection
    sql = "SELECT [DESCRIP] FROM tbl_setpoints_categories ORDER BY [ORD] ASC;"

    rs.Open sql, con

    If Not (rs.EOF And rs.BOF) Then
       rs.MoveFirst
       Do While Not rs.EOF
          selectItems.Add rs!DESCRIP
          rs.MoveNext
       Loop
    Else
    End If

    rs.Close
    con.Close
    Set rs = Nothing
    Set con = Nothing


    MsgBox(selectItems.Count)  '<--- produces 20 items

    'myCol is a collection (passed in this sub) of object names that will be used to produce controls
    For Each x in myCol

        selName = "sel" & x & "-" & i
        Set xSel = frm_new_setpoints.Controls.Add("Forms.ComboBox.1", selName, True)
        With xSel
            .Width = 120
            .Left = 384
            .Height = 18
            .Top = 44 + (i * 30)

        End With

        For Each sItem In selectItems
            xSel.AddItem sItem
        Next sItem

     i = i + 1
   Next x

   'Show the form with new controls
   frm_new_setpoints.Show

   Set xSel = Nothing


End Sub

1 个答案:

答案 0 :(得分:2)

您的代码没有任何问题。这是填充动态创建的组合框的正确方法。我相信你的记录集正在为你的收藏品填充空白项目,因此你在组合框中得到空白值。

参见此示例

Private Sub CommandButton1_Click()
    Dim col As New Collection, itm As Variant
    Dim xSel As Object

    col.Add " "
    col.Add "  "
    col.Add "   "
    col.Add " "

    Set xSel = UserForm2.Controls.Add("Forms.ComboBox.1", "Sid", True)

    With xSel
        .Width = 120
        .Left = 384
        .Height = 18
        .Top = 44

        For Each itm In col
            .AddItem itm
        Next itm
    End With

    UserForm2.Show
    Set xSel = Nothing
End Sub

enter image description here

现在如果你更换

    col.Add " "
    col.Add "  "
    col.Add "   "
    col.Add " "

通过

    col.Add "1"
    col.Add "2"
    col.Add "3"
    col.Add "4"

然后您将看到组合框中填充的值。

enter image description here

注意

如果更改了行

selectItems.Add rs!DESCRIP 

If Len(Trim(rs!DESCRIP)) <> 0 Then selectItems.Add rs!DESCRIP

然后你会注意到MsgBox(selectItems.Count)将不再给你20。