简体   繁体   中英

Create queries based on information in a table

I have some knowledge of Access and VBA programming, but I stress some . I haven't really used Access since college.

I have a table called Location with 2 fields: Postcode and a Group Code . This list has 1,693,353 records.

I have another table called Group with 2 fields: Group Name and Group Code . There are about 300 different Authority Records.

I need to make a table/query for each Group and have the different location postcodes in the tables.

I know that I could go through and make 300 different queries all with the Group code as the criteria and that would match them up, but that means making 300 different queries.

What I would like to know is if there is a way of automating this process. I'm not asking for people to create it for me (unless they want to) but if there are any guides or tutorials that people could recommend for learning Access VBA that would help as well.

This query will contain all your groups (I've named it SQL_Group) SELECT GroupName, Postcode FROM [Group] INNER JOIN Location ON Group.GroupCode = Location.GroupCode will create your groups.

This code will cycle through each group:

Public Sub FilterQuery()

    Dim qdf As DAO.QueryDef
    Dim rst As DAO.Recordset
    Dim rst_Groups As DAO.Recordset
    Dim rst_Filtered As DAO.Recordset
    Dim db As DAO.Database

    Set db = CurrentDb

    Set qdf = db.QueryDefs("SQL_Group")
    Set rst = qdf.OpenRecordset
    Set rst_Groups = db.OpenRecordset("Group")

    With rst_Groups
        If Not (.BOF And .EOF) Then
            .MoveFirst
            Do While Not .EOF
                rst.Filter = "GroupName = '" & rst_Groups.Fields("GroupName") & "'"
                Set rst_Filtered = rst.OpenRecordset
                With rst_Filtered
                    If Not (.BOF And .EOF) Then
                        .MoveFirst
                        Do While Not .EOF
                            Debug.Print .Fields("GroupName") & " : " & .Fields("PostCode")
                            .MoveNext
                        Loop
                    End If
                    .Close
                End With
                .MoveNext
            Loop
        End If
        .Close
    End With

    Set rst_Filtered = Nothing
    Set rst = Nothing
    Set rst_Groups = Nothing

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM