我有一个包含包含文本的列的数据透视表。我还有5个选项按钮。通过VBA代码我想过滤一个数据透视表的列,如果它包含某个文本。我需要五个不同的包含函数来解释各种组合。然后我计划将这些宏分配给选项按钮。我浏览了各种各样的论坛,但是无法按照他们的描述使其工作,而且他们从来没有完全按照我在这里描述的方式构建它。
这是我目前为3个按钮所做的,但是当我点击一个按钮到另一个按钮时出现错误:
Sub Incr_Phys()
'
' Incr_Phys Macro
'
'
ActiveSheet.PivotTables("PivotTable1").PivotFields("Eligible Win Type"). _
PivotFilters.Add2 Type:=xlCaptionContains, Value1:="Incr Phys"
Selection.End(xlToLeft).Select
Selection.End(xlUp).Select
End Sub
Sub All_Win_Types()
'
' All_Win_Types Macro
'
'
ActiveSheet.PivotTables("PivotTable1").PivotFields("Eligible Win Type"). _
PivotFilters.Add2 Type:=xlCaptionContains, Value1:="?"
Selection.End(xlToLeft).Select
Selection.End(xlUp).Select
Selection.End(xlToLeft).Select
Selection.End(xlUp).Select
End Sub
Sub Acq()
'
' Acq Macro
'
'
ActiveSheet.PivotTables("PivotTable1").PivotFields("Eligible Win Type"). _
ClearAllFilters
ActiveSheet.PivotTables("PivotTable1").PivotFields("Eligible Win Type"). _
PivotFilters.Add2 Type:=xlCaptionContains, Value1:="Acq"
Selection.End(xlToLeft).Select
Selection.End(xlUp).Select
Selection.End(xlToLeft).Select
Selection.End(xlUp).Select
End Sub
答案 0 :(得分:0)
很明显,您已经录制了一个宏来捕获VBA作为从哪里开始的示例。非常好的举动,因为这可以揭示一些你不会知道的方法。完成后,您可以采取一些措施来帮助调试代码并帮助更清楚地了解正在发生的事情。
Activate
和Select
。 Worksheets
和Workbooks
的引用。当您尝试扩展工作时,它将帮助您避免以后出现问题。PivotTable
在重新应用新过滤器之前,我认为您缺少的是ClearAllFilters
。
Option Explicit
Sub Incr_Phys()
'
' Incr_Phys Macro
'
Dim thisWB As Workbook
Dim pivotWS As Worksheet
Set thisWB = ThisWorkbook
Set pivotWS = thisWB.Sheets("Sheet5")
Dim thisPT As PivotTable
Dim winType As PivotField
Set thisPT = pivotWS.PivotTables("PivotTable1")
Set winType = thisPT.PivotFields("Eligible Win Type")
With winType
.ClearAllFilters
.PivotFilters.Add2 Type:=xlCaptionContains, Value1:="Incr Phys"
End With
End Sub