【发布时间】:2016-08-19 15:38:26
【问题描述】:
我正在我的用户表单中动态创建组合框,我想将相同的项目添加到表单上的每个组合框。
我创建了一个项目集合(从 sql 语句和 Access DB 中查询)。然后在创建组合框对象后,我在集合内的每个项目中执行for each 语句以添加到组合框,但组合框不填充!控件已创建,但组合框为空
我检查了集合,看看我是否获得了价值。 (请参阅我查询收集计数的行),我得到了 20 个正确的项目。
我做错了什么?
EDIT - 我最近在调用显示表单的父 For Each 循环的末尾添加了代码。这可能是表单无法正确显示的原因...
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
【问题讨论】:
-
我刚刚在一个新的用户表单和一个自定义集合中测试了你的代码。你的代码对我有用。
-
嗯...让我添加更多代码(我认为它不会影响它)。
-
你从哪里运行代码?
-
该子程序正在从不同的表单运行。我刚刚添加了调用要显示的新表单的其余代码。这就是组合框没有填充的原因吗?
-
不。它仍然对我有用:)
标签: excel for-loop collections combobox vba