2016-10-20 96 views
0

篩選數據透視表,我用下面的代碼工作:與複選框

Option Explicit 
Sub checkboxfilter() 
    Dim cb As CheckBox 
    Dim oWS As Worksheet 
    Dim oWB As Workbook 
    Dim oPvt As PivotTable 
    Dim oPvtField As PivotField 
    Dim oPvtFilter As PivotFilter 


    Set cb = oWS("Control").Controls("YTD Filter") 

If cb.Value = True Then 
    For Each oWS In ThisWorkbook.Worksheets 
     For Each oPvt In oWS 
      With oPvtField 
      .CurrentPage.Name = "Yes" 
      End With 
     Next oPvt 
    Next oWS 
End If 

End Sub 

的目標是通過複選框中揭掉最新的過濾器來切換工作簿中的每個數據透視表。代碼在set cb=作爲對象變量或未設置時遇到障礙。我在這裏錯過了什麼讓這個控制工作?我也避免使用切片機。

謝謝。

回答

0

這種控制有它自己的事件,你應該使用它。因此:

  1. 轉到表,你有你的複選框
  2. 設置Design mode開發人員選項卡上
  3. check box到雙擊...
  4. ...看到類似Private Sub CheckBox1_Click()
  5. 裏面的那個子調用你的子程序:

    Private Sub CheckBox1_Click() 
        call checkboxfilter 
    End Sub 
    
+0

謝謝,雖然沒有解決上述代碼的過濾。 – GregdeLima

+0

你問過如何用複選框來觸發動作:)在查看你的代碼時,似乎你仍然必須鏈接你的'oPvt'和數據透視表字段。此時'oPvtField'似乎是'Nothing'。 –

0

我能夠基於調整格式set cb =的類型作爲.Checkboxes並且在每個樞轉fielt確保被正確地稱爲@KazimierzJawor指出修改。此外,此類型的值需要爲0或1,而不是TrueFalse。下面更正和最終的代碼。

Private Sub checkboxfilter() 
    Dim cb As CheckBox 
    Dim oWS As Worksheet 
    Dim oWB As Workbook 
    Dim oPvt As PivotTable 
    Dim oPvtField As PivotField 
    Dim oPvtFilter As PivotFilter 


Set cb = Sheets("Control").CheckBoxes("YTD Filter") 

If cb.Value = 1 Then 
    For Each oWS In ThisWorkbook.Worksheets 
     For Each oPvt In oWS.PivotTables 
      With oPvt.PivotFields("YTD?") 
      .CurrentPage = "Yes" 
      End With 
     Next oPvt 
    Next oWS 
    Else 
      For Each oWS In ThisWorkbook.Worksheets 
      For Each oPvt In oWS.PivotTables 
       With oPvt.PivotFields("YTD?") 
       .CurrentPage = "(All)" 
       End With 
      Next oPvt 
     Next oWS 
End If 

End Sub