使用xlValueIsBetween作为pivot值的Excel VBA

我正在尝试创build一个模块,以在单个工作簿中的多个工作表上共享function。 除了一些过滤代码,所有的工作都很好。

下面的代码工作正常,如果我把它放在一个工作表中

ActiveSheet.PivotTables("PivotTable1").PivotFields("MyField"). _ ClearValueFilters ActiveSheet.PivotTables("PivotTable1").PivotFields("MyField").PivotFilters.Add Type:=xlValueIsBetween, DataField:=ActiveSheet.PivotTables _ ("PivotTable1").PivotFields("MyValue"), Value1:=bottom, Value2:=Top 

但是,我想在我的模块中使用此代码,并发送以下内容:

数据透视表名称,
行数据透视图字段,
Value Pivot字段
“之间”的价值
底部“之间”值

就像是:

表单调用

 Call Mod_Filter("PivotTable1", "MyRowFieldName", "MyValueFieldName", 0, intvalue) 

模块代码

 Public Sub Mod_Filter(ByRef PT_Name As String, ByRef StaticField As String, ByRef Filter_field As String, bottom As Double, Top As Double) ActiveSheet.PivotTables(PT_Name).PivotFields(StaticField).ClearValueFilters ActiveSheet.PivotTables(PT_Name).PivotFields(StaticField).PivotFilters.Add Type:=xlValueIsBetween, DataField:=ActiveSheet.PivotTables _ (PT_Name).PivotFields(Filter_field), Value1:=bottom, Value2:=Top End Sub 

但是,我无法得到这个工作。 有什么build议么??

在这里输入图像说明

因此,我使用“St”行来根据从下拉combobox中select的值过滤YTD%

要求:基于透视数据RowField过滤数据透视RowField

此过程使用PivotField.SourceName来validation并设置DataField以应用filtertypes和值。

 Sub Ptb_Filter_Between(WshTrg As Worksheet, _ sFldTrg As String, sFldDta As String, dFromVal As Double, dToValue As Double) Dim pTbl As PivotTable, pFldDta As PivotField Rem Application Settings - OFF Application.ScreenUpdating = False Application.EnableEvents = False Rem Set PivotTable 'Using Index 1 as OP confirmed there is only one PivotTable per Sheet 'If this condition change then PivotTable Index should be provided as an argument Set pTbl = ActiveSheet.PivotTables(1) With pTbl Rem Set DataField - User provides the Data Field For Each pFldDta In .DataFields If pFldDta.SourceName = sFldDta Then Exit For Next If pFldDta Is Nothing Then GoTo ExitTkn Rem Filter PivotField .ClearAllFilters 'Use this line to clear all PivotTable Filters On Error GoTo ExitTkn With .PivotFields(sFldTrg) .ClearAllFilters 'This line clears all PivotField Filters .PivotFilters.Add2 Type:=xlValueIsBetween, _ DataField:=pFldDta, Value1:=dFromVal, Value2:=dToValue End With: End With ExitTkn: Rem Application Settings - ON Application.ScreenUpdating = True Application.EnableEvents = True End Sub 

这些是如何调用该过程的一些示例:

 sFldTrg = "Type" sFldDta = "Amount" dFromVal = 25000 dToValue = 30000 Call Ptb_Filter_Between(Worksheet Object, sFldTrg, sFldDta, dFromVal, dToValue) sFldTrg = "Type" sFldDta = "YTD%" dFromVal = 0.3 dToValue = 0.35 Call Ptb_Filter_Between(Worksheet Object, sFldTrg, sFldDta, dFromVal, dToValue) sFldTrg = "Row" sFldDta = "YTD%" dFromVal = 0.1 'To set from value as 10% dToValue = 0.2 'To set to value as 20% Call Ptb_Filter_Between(Worksheet Object, sFldTrg, sFldDta, dFromVal, dToValue)