如何用查询结果填充组合框

时间:2019-06-19 09:33:49

标签: ms-access access-vba

我在访问vba中从查询结果填充ComboBox时遇到问题。我的目标是查询表的一列,并将结果中的每条记录用作组合框的选项。

关于ComboBoxes的属性,您需要了解一些事情,并进行适当的分配才能使此工作正常进行。这是我的代码,似乎包含正确的信息,但在下拉列表中未显示任何内容:

Dim RS As DAO.Recordset
Dim SQL As String

'Clean-up. not sure if it's needed but I'm "clearing" the old data (if there's any) before putting the new in
combox.RowSourceType = "Table/Query"
combox.RowSource = ""

SQL = "SELECT [some_value] FROM [a_table] WHERE [another_value] = '" & argv(0) & "'"

combox.RowSource = SQL

这是我问的another question的一部分,但为了更清晰的结构,我将此问题(及其答案)移到了该线程中。

2 个答案:

答案 0 :(得分:1)

您的第一次尝试很好,您只需要重新查询组合框即可实际加载查询结果。

Dim SQL As String
combox.RowSourceType = "Table/Query"
combox.RowSource = ""

SQL = "SELECT [some_value] FROM [a_table] WHERE [another_value] = '" & argv(0) & "'"

combox.RowSource = SQL
combox.requery 'Clears old data, loads new data

答案 1 :(得分:0)

经过一些重构和修复后,我得出了以下结果,该结果使ComboBox的行为符合我的预期:

combox.RowSourceType = "Value List"
combox.RowSource = ""


SQL = "SELECT [some_value] FROM [a_table] WHERE [another_value] = '" & argv(0) & "'"
With combox
    .RowSource = kombSQL
    .ColumnCount = 2
    .ColumnWidth = 1
    .ColumnWidths = "1.5in."
End With

Set RS = CurrentDb.OpenRecordset(SQL)
RS.MoveLast
RS.MoveFirst
combox.RemoveItem 0

Do Until RS.EOF
    Me.combox.AddItem RS.Fields("some_value")
    RS.MoveNext
Loop

RS.Close
Set RS = Nothing

Me.combox.BoundColumn = 0
Me.combox.ListIndex = 0