VBA - 循环多个记录集

时间:2017-07-15 23:06:34

标签: vba ms-access recordset

我想我有一个相当简单的问题要回答。下面的代码完全按原样运行,最终结果是使用来自Access数据库的字段数据填充了2个userform的组合框。我还有几个组合框来填充访问数据。我正在寻找一种方法来循环单个记录集中的多个SQL语句,而不是需要为每个SQL查询创建一个新的记录集。一如既往,非常感谢。

Const conStrAccess As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data 
Source=C:\Users\Andy\Desktop\Database\IATC.accdb;Persist Security 
Info=False;"
Const providerSQL As String = "SELECT DISTINCT [Provider Name] FROM 
tblProvider ORDER BY [Provider Name];"
Const employeeSQL As String = "SELECT DISTINCT [Employee Name] FROM 
tblEmployee ORDER BY [Employee Name];"    

Dim aConn As ADODB.Connection
Dim providerData As ADODB.Recordset
Dim employeeData As ADODB.Recordset

Set aConn = New ADODB.Connection
Set providerData = New ADODB.Recordset
Set employeeData = New ADODB.Recordset

aConn.ConnectionString = conStrAccess
aConn.Open

aConn.ConnectionString = conStrAccess
aConn.Open

providerData.Open providerSQL, aConn, adOpenStatic, adLockReadOnly
providerData.MoveFirst

With Me.cbxProvider
    .Clear
    Do
        .AddItem providerData![Provider Name]
        providerData.MoveNext
    Loop Until providerData.EOF
End With

employeeData.Open employeeSQL, aConn, adOpenStatic, adLockReadOnly
employeeData.MoveFirst

With Me.cbxEmployee
    .Clear
    Do
        .AddItem employeeData![Employee Name]
        employeeData.MoveNext
    Loop Until employeeData.EOF
End With

2 个答案:

答案 0 :(得分:3)

考虑不使用任何记录集,因为MS Access表单组合框和列表框可以使用表和查询作为行源:

Dim var As Variant, varList As Variant

varList = Array("Provider", "Employee")

For Each var in varList

    sql = "SELECT DISTINCT [" & var & " Name] " _
           & " FROM tbl" & var & " ORDER BY [" & var & " Name];"

    With Me.Form.Controls("cbx" & var)
        .RowSourceType = "Table/Query"
        .RowSource = sql
        .Requery
    End With

Next var

答案 1 :(得分:2)

在编程中,一个有用的经验法则是“不要重复自己”(“干”)。如果您发现您使用一致的变体一遍又一遍地编写相同的代码,那么您应该将该代码重构为一个单独的方法,并使用一些参数来管理变体。

未测试:

Sub Main()

    Const conStrAccess As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data " & _
        "Source=C:\Users\Andy\Desktop\Database\IATC.accdb;Persist Security Info=False;"

    Const providerSQL As String = "SELECT DISTINCT [Provider Name] FROM tblProvider ORDER BY [Provider Name]"
    Const employeeSQL As String = "SELECT DISTINCT [Employee Name] FROM tblEmployee ORDER BY [Employee Name]"

    Dim aConn As New ADODB.Connection
    aConn.Open conStrAccess

    FillListBox aConn, providerSQL, Me.cbxProvider
    FillListBox aConn, employeeSQL, Me.cbxEmployee
    '...more lists...

    aConn.Close

End Sub

'Fill a combobox from a single-field SQL query
Sub FillComboBox(con As ADODB.Connection, SQL As String, cb)
    Dim rs As New ADODB.Recordset
    rs.Open SQL, con, adOpenStatic, adLockReadOnly
    With cb
        .Clear
        Do While Not rs.EOF
            .AddItem rs.Fields(0).Value
            rs.MoveNext
        Loop
    End With
    rs.Close
End Sub