使用Access VBA查找不同的值集

时间:2016-11-16 18:32:05

标签: vba access-vba distinct-values

我希望从MS Access中的多个表中的某些字段的集合中找到不同的值列表。但是,我的VBA代码只返回每个字段的第一个值(而不是每个字段中的完整不同值集合)。请参阅以下内容:

Sub GetDistinctValues()

    Dim tbl As DAO.TableDef
    Dim fld As DAO.Field
    Dim rs As DAO.Recordset
    Dim rs1 As DAO.Recordset

    Set rs = CurrentDb.OpenRecordset("Fields_To_Examine")

    Do While Not rs.EOF
    For Each tbl In CurrentDb.TableDefs

        If tbl.Name = rs("Table_Name") Then
        Debug.Print tbl.Name

            For Each fld In tbl.Fields
                If fld.Name = rs("Field_Name") Then
                Debug.Print fld.Name

                    Set rs1 = CurrentDb.OpenRecordset("SELECT DISTINCT " & tbl.Name & ".Source_System, " & tbl.Name & "." & fld.Name & " FROM " & tbl.Name)
                    Debug.Print rs1(0), rs1(1)

                    rs.MoveNext

                End If
            Next
         End If
    Next
    Loop

    rs.Close
    rs1.Close

    Set rs = Nothing
    Set rs1 = Nothing

    End Sub

关于我哪里出错的任何建议?

1 个答案:

答案 0 :(得分:1)

MoveNext在字段循环中,所以:

For Each tbl In CurrentDb.TableDefs

    If tbl.Name = rs("Table_Name") Then
    Debug.Print tbl.Name

        For Each fld In tbl.Fields
            If fld.Name = rs("Field_Name") Then
            Debug.Print fld.Name

                Set rs1 = CurrentDb.OpenRecordset("SELECT DISTINCT " & tbl.Name & ".Source_System, " & tbl.Name & "." & fld.Name & " FROM " & tbl.Name)
                Debug.Print rs1(0), rs1(1)

            End If
        Next
     End If
Next
rs.MoveNext