2013-03-22 61 views
1

我有一個連續的訪問形式,在標題中有3個組合框來過濾數據。目前我有一個相當長的嵌套IF來檢查多少組合框正在使用,並涵蓋所有8個滲透。有3盒不是也不是不好,但我可能會增加第4或甚至第5,在這種情況下它會變得荒謬。訪問形式的動態編碼過濾器

是否有更簡單的方法來設置連續窗體的組合框過濾器?

目前代碼

Private Sub filters() 
    Dim fstr As String, rgS As String, piS As String, hcS As String 
    rgS = "research_group_id = " & Me.fRG 
    piS = "pi_id = " & Me.fPI 
    hcS = "healthcat_id = " & Me.fHC 
    If IsNull(Me.fRG) Then 
     If IsNull(Me.fPI) Then 
      If IsNull(Me.fHC) Then 
       ' Do Nothing 
      Else 
       fstr = hcS 
       Call filton(Me.Name, fstr) 
      End If 
     Else 
      If IsNull(Me.fHC) Then 
       fstr = piS 
       Call filton(Me.Name, fstr) 
      Else 
       fstr = piS & " AND " & hcS 
       Call filton(Me.Name, fstr) 
      End If 
     End If 
    Else 
     If IsNull(Me.fPI) Then 
      If IsNull(Me.fHC) Then 
       fstr = rgS 
       Call filton(Me.Name, fstr) 
      Else 
       fstr = rgS & " AND " & hcS 
       Call filton(Me.Name, fstr) 
      End If 
     Else 
      If IsNull(Me.fHC) Then 
       fstr = rgS & " AND " & piS 
       Call filton(Me.Name, fstr) 
      Else 
       fstr = rgS & " AND " & piS & " AND " & hcS 
       Call filton(Me.Name, fstr) 
      End If 
     End If 
    End If 
End Sub 

上面的代碼中每個組合框的更新後解僱。

Public Function filton(frmname As String, fstr As String) 
     With Forms(frmname) 
      .FilterOn = False 
      .Filter = fstr 
      .FilterOn = True 
     End With 
End Function 

回答

1

將每個條件與" AND "一起添加到您的過濾器字符串中。之後,丟棄該字符串中的前導" AND "。這種方法應該容易適應任何數量的標準。

不知道我是否在下面的代碼中正確匹配了所有內容,但希望模式清晰。

If Not IsNull(Me.fRG) Then 
    fstr = fstr & " AND " & rgS 
End If 
If Not IsNull(Me.fPI) Then 
    fstr = fstr & " AND " & piS 
End If 
If Not IsNull(Me.fHC) Then 
    fstr = fstr & " AND " & hcS 
End If 
If Len(fstr) > 0 Then 
    ' discard leading " AND " 
    fstr = Mid(fstr, 6) 
End If 
+0

非常好。開始時沒有想到它會起作用,但忘了在最後添加「Call Filton(me.name,fstr)」。非常感謝! – 2013-03-22 10:24:45

+1

沒有看到已刪除的評論,但沒有'vbnullstring',它工作正常。 – 2013-03-22 10:50:08

1

您可以在組合框上創建After Update事件。這是一個3層的層次結構,其中親子組合框上的負載

Private Sub Grandfather_Combo_AfterUpdate() 

    Parent_Combo.RowSource="SELECT ...." 
    Parent_Combo.Enabled=True 
    Child_Combo.Enabled=False  ' the child is invalid until the parent is defined 

End Sub 

Private Sub Parent_Combo_AfterUpdate() 

    Child_Combo.RowSource="SELECT ...." 
    Child_Combo.Enabled=True 

End Sub 

這是一個單記錄表禁用的例子,但應該讓你開始,如果這是你想要的組合框更改。

如果它是您想要更改的記錄過濾器,則使用相同的事件,而是更改相關字段的過濾器變量,然後調用常用子過程以從所有過濾器變量的組合重新創建表單過濾器。

+0

對不起,我應該說每個組合框更新後上面的代碼被激發 – 2013-03-22 10:12:23

+0

好吧,我支持我的立場。個別AfterUpdate()設置了form_level變量,通用子程序來更改過濾器。 – grahamj42 2013-03-22 10:26:16

+0

組合框不分層,用戶可以以任意組合選擇1,2或3。 – 2013-03-22 10:28:49