【问题标题】:Apply filter to query for combobox based on field in current form应用过滤器以根据当前表单中的字段查询组合框
【发布时间】:2021-05-18 05:53:32
【问题描述】:

在我的数据库的简化版本中,假设我有 3 个表:Company、WorkUnit、Personel

  • 公司字段:cID (PK)、cName
  • 工作单元字段:wID (PK)、wcID (FK)、wName
  • 人员字段:pID (PK)、pcID (FK)、pwID (FK)、pName

因此,这是如何运作的,您在第一张桌子上有几家公司。在第二张表中,您有几个属于一家公司的工作单位(同一公司有多个工作单位,有时只有一个或没有)。在第三张表中,您有属于公司或属于公司和工作单位的人员(当然,这个工作单位必须是一个,属于您为该人选择的公司)。

所有外键实际上都是文本,而不是数字(例如,cID 为 3 的公司名为 Fruit Factory,因此在 Personel pcID 字段中您不写 3,而是写“Fruit Factory”)。

我还有一个名为 qryWorkUnits(字段是 wID、wName、wcID)的查询,用于我的“实时过滤”,它适用于以下代码:

'Module
Public Sub FilterComboAsYouType(combo As ComboBox, defaultSQL As String, lookupField As String)
Dim strSQL As String
    If Len(combo.Text) > 0 Then
        strSQL = defaultSQL & " WHERE " & lookupField & " LIKE '*" & combo.Text & "*'"
    Else
        strSQL = defaultSQL    'This is the default row source of combo box
    End If
    combo.RowSource = strSQL
    combo.Dropdown
End Sub
'form for Personel table
Private Sub pwID_Change()
FilterComboAsYouType Me.pwID, "SELECT * FROM qryWorkUnits", "wName"
End Sub

现在,它的作用是在我写的时候过滤我的组合框,以便缩小我的选择范围。但这意味着它为我提供了与我的写作相匹配的所有 WorkUnit,无论该 WorkUnit 属于哪个公司。我试图在该代码中插入各种不同的部分,但我无法让它根据我在 Personel 表单中选择的 cID 过滤查询。肯定有可能以某种方式做到这一点?

【问题讨论】:

    标签: sql vba ms-access


    【解决方案1】:

    我找到了解决办法。我需要编辑一些代码,现在它可以正常工作了。 这是最终代码:

    Public Sub FilterComboAsYouType(combo As ComboBox, defaultSQL As String, lookupField As String, idField As String)
    Dim strSQL As String
    Dim curID As String
    curID = Me.pcID
        If Len(combo.Text) > 0 Then
            strSQL = defaultSQL & " WHERE " & lookupField & " LIKE '*" & combo.Text & "*' AND " & idField & "=" & curID
        Else
            strSQL = defaultSQL    'This is the default row source of combo box
        End If
        combo.RowSource = strSQL
        combo.Dropdown
    End Sub
    
    
    Private Sub pwID_Change()
    FilterComboAsYouType Me.pwID, "SELECT * FROM qryWorkUnits", "wName", "wcID"
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2017-07-30
      • 2016-07-20
      • 2015-07-26
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多