Microsoft Access - 表单列表框,用于过滤一对多关系值的报告

时间:2017-01-05 15:41:33

标签: vba ms-access access-vba

我有三张桌子;应用程序,区域和ApplicationRegionJoin。应用程序可以通过连接表包含许多区域,该表仅存储ApplicationID和RegionID。我有一个查询将所有应用程序拖到报表和表单上,用户可以通过命令按钮输入用于运行报表的过滤器参数。我可以成功地使用多选列表框来根据应用程序上的值进行过滤,但我仍然坚持如何使用列表框根据区域进行过滤。这可能吗?

编辑:这是我目前使用两个单独的多选列表框在应用程序中基于两个单独列进行过滤的VBA代码。我对VBA来说比较新,所以请原谅我们缺乏干活或其他缺乏最佳实践等。

Private Sub RunApplicationReport_Click()

    DoCmd.Close acReport, "Application Report"

    Dim strWhere As String
    Dim str As String
    Dim ctl As Control
    Dim varItem As Variant

    strWhere = vbNullString

    If Me.listStatuses.ItemsSelected.Count > 0 Then
        If strWhere <> vbNullString Then strWhere = strWhere & " AND "
        'add selected values to string
        Set ctl = Me.listStatuses
        For Each varItem In ctl.ItemsSelected
        str = str & "'" & ctl.ItemData(varItem) & "',"
        Next varItem
        'trim trailing comma
        str = Left(str, Len(str) - 1)
        'open the report, restricted to the selected items
        strWhere = strWhere & "BidStatuses.BidStatus IN(" & str & ")"
    End If
    If Me.listCategories.ItemsSelected.Count > 0 Then
        If strWhere <> vbNullString Then strWhere = strWhere & " AND "
        'add selected values to string
        Set ctl = Me.listCategories
        For Each varItem In ctl.ItemsSelected
        str = str & "'" & ctl.ItemData(varItem) & "',"
        Next varItem
        'trim trailing comma
        str = Left(str, Len(str) - 1)
        'open the report, restricted to the selected items
        strWhere = strWhere & "Categories.Category IN(" & str & ")"
    End If

    DoCmd.OpenReport ("Application Report"), acViewPreview, , strWhere

End Sub

1 个答案:

答案 0 :(得分:0)

以下是我提出的解决方案。基本上,它从表单列表框中构建一个逗号分隔的选定区域名称字符串(类似于上面的其他列表框代码),然后从连接表创建ApplicationID的记录集,其中RegionID等于Regions表中的ID,其中区域名称等于该字符串中的值。然后更新report where子句以过滤匹配的ApplicationID。

If Me.listRegions.ItemsSelected.Count > 0 Then

        Dim regs As String
        regs = vbNullString
        Set ctl = Me.listRegions
        For Each varItem In ctl.ItemsSelected
            regs = regs & "'" & ctl.ItemData(varItem) & "',"
        Next varItem
        regs = Left(regs, Len(regs) - 1)

        Dim rs As DAO.Recordset
        Set rs = CurrentDb.OpenRecordset("SELECT ApplicationID FROM ApplicationRegionJoin WHERE RegionID IN(" & _
        "SELECT ID FROM Regions WHERE Region IN(" & regs & "))") 'because listRegions is bound to Region (the region name) not the ID from Regions

        Dim apps As String
        apps = vbNullString

        If Not (rs.EOF And rs.BOF) Then
            rs.MoveFirst
            Do Until rs.EOF = True
                apps = apps & rs!ApplicationID & ","
                rs.MoveNext
            Loop

            rs.Close
            Set rs = Nothing

        End If

        If strWhere <> vbNullString Then strWhere = strWhere & " AND "
        strWhere = strWhere & "Applications.ID IN(" & apps & ")"

    End If