使用SQL查询结果填充列表框

时间:2014-04-01 00:36:07

标签: sql vba listbox ms-access-2010 recordset

好吧,如果我尝试过的话,我可能会离开,但是在这里。我正在尝试执行SQL查询以返回一些记录,然后填充列表框。基本上,我希望每条记录都显示在一个单独的行中。我在一个引用主窗体的单独模块中有这个。我听说过一些关于用SQL结果填充数据表然后将列表框链接到那个的事情,但我不是100%确定要做什么。我刚刚尝试用每个结果手动更新列表框,但它似乎不喜欢它。我正在使用记录集而不是数据表,但就像我说的那样,这是因为我不确定如何使用数据表(之前没有这样做但我愿意学习)

Public Sub addCases()
'Uses windows login credentials to determine and return CSP's Manager's Name

'C
Dim i As Integer
Dim intX As Integer


Dim c As ADODB.Connection
Dim r As ADODB.Recordset
Dim strSQL As String, strManager As String
Set c = New ADODB.Connection
c.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Commit Tracker.accdb; Persist Security Info=False;"
strSQL = "SELECT "
    strSQL = strSQL & "* "
strSQL = strSQL & "FROM "
    strSQL = strSQL & "CommitTrk "
strSQL = strSQL & "WHERE "
    strSQL = strSQL & "EMP_ID = '" & Username() & "'"
Set r = c.Execute(strSQL)

If r.EOF = False Then
    intX = 0
    vararray = r.GetRows()
    For i = LBound(vararray) To UBound(vararray)
       With frmCommitViewer.lstCases
           .AddItem
           .List(intX, 0) = r.Index(i)
       End With
       intX = intX + 1
    Next i
End If
r.Close
c.Close
Set r = Nothing
Set c = Nothing


End Sub

1 个答案:

答案 0 :(得分:1)

我明白了。而不是愚蠢的数组转换,我仍然直接使用记录集。

If r.EOF = False Then
    With frmCommitViewer.lstCases
        .Clear
        Do
            .AddItem r![CASE_ID_NBR]
            r.MoveNext
        Loop Until r.EOF
    End With
End If

超级简单。感谢http://www.fontstuff.com/vba/vbatut10pfv.htm

相关问题