2016-04-07 41 views
1

我在製作一個小程序。在主表上,有兩個組合框。使用多個條件篩選值的代碼

我想要做的,如果我從每個組合框中選擇值,它會過濾數據。但是我面臨一個小問題。我想在兩個組合框中都有一個ALL值,並且在選擇該值時不應該過濾該列。

到目前爲止,我的代碼是這樣的:

Sub submit() 

    Dim ws As Worksheet, tbl As ListObject, rng As Range 

    Set ws = Sheets("Graphical Summary") 
    Set tbl = ws.ListObjects("Table5") 
    Set rng = tbl.DataBodyRange 

    With tbl 
     .Range.AutoFilter Field:=1 
     .Range.AutoFilter Field:=3 
    End With 

     With rng 
      If Sheets("Graphical Summary").ComboBox1.Value = "All"  Then .AutoFilter Field:=2, Criteria1:=Sheets("Graphical Summary").ComboBox2.Value 
      If Sheets("Graphical Summary").ComboBox1.Value <> vbNullString Then .AutoFilter Field:=1, Criteria1:=Sheets("Graphical Summary").ComboBox1.Value 
      If Sheets("Graphical Summary").ComboBox2.Value <> vbNullString Then .AutoFilter Field:=2, Criteria1:=Sheets("Graphical Summary").ComboBox2.Value 
     End With 
End Sub 

回答

0

目前,您沒有設置現場1的過濾器,如果ComboBox1是零長度字符串;將該條件延伸至包括全部

With rng 
    If ws.ComboBox1.Value <> vbNullString And 
     ws.ComboBox1.Value <> "All" Then _ 
     .AutoFilter Field:=1, Criteria1:=ws.ComboBox1.Value 
    If ws.ComboBox2.Value <> vbNullString Then _ 
     .AutoFilter Field:=2, Criteria1:=ws.ComboBox2.Value 
End With 

您已經聲明WS並將其分配給表( 「圖形摘要」);你不妨使用它。