我试图一次过滤多个数据透视表。错误发生在以pt.PivotFields...
开头的行上,不知道为什么它不起作用:
Sub PivotFilter()
Application.ScreenUpdating = False
Dim table As String
Dim tablenum As Integer
Dim comptable As String
table = "CD"
Dim Col1 As Integer
Dim Col2 As Integer
Dim Rng1 As Range
Dim Rng2 As Range
Dim Dt1 As Date
Dim Dt2 As Date
Dim pt As PivotTable
For tablenum = 2 To 61
comptable = table & tablenum
Col1 = tablenum * 2 + tablenum - 2
Col2 = tablenum * 2 + tablenum - 1
Set Rng1 = Sheets("Sheet2").Cells(1, Col1)
Set Rng2 = Sheets("Sheet2").Cells(1, Col2)
Dt1 = Rng1.Value
Dt2 = Rng2.Value
Set pt = ActiveSheet.PivotTables(comptable)
pt.PivotFields("Maturity Date").PivotFilters.Add Type:=xlDateBetween, Value1:=Rng1, Value2:=Rng2
Next tablenum
Application.ScreenUpdating = False
End Sub
答案 0 :(得分:0)
我有两个猜测可能是什么问题:
这应该解决两个/两个:
Dim d1, d2 as Date
d1 = CDate(Rng1.Value);
d2 = CDate(Rng2.Value);
Set pt = ActiveSheet.PivotTables(comptable)
pt.PivotFields("Maturity Date").ClearAllFilters
pt.PivotFields("Maturity Date").PivotFilters.Add _
Type:=xlDateBetween, Value1:=d1, Value2:=d2
答案 1 :(得分:0)
添加数据透视表
此错误是由于使用了错误的Data Type
将参数传递给PivotFilters.Add2
方法。您使用Date
代替Variant
(请参阅PivotFilters.Add2 Method (Excel))
以下是您的原始代码,其中包含一些修改以更正Data Type
问题和其他次要更改(在代码中注释)。还建议用对象变量替换activesheet
。
Sub PivotFilters_Add2()
Rem Suggest to use a constant instead of a variable
Const kTable As String = "CD"
Dim pt As PivotTable
Dim comptable As String
Rem Suggest to use Byte for numbers ranging in value from 0–255.
Dim tablenum As Byte, Col1 As Byte, Col2 As Byte
Dim vDte1 As Variant, vDte2 As Variant
Application.ScreenUpdating = False
For tablenum = 2 To 61
comptable = kTable & tablenum
Col1 = tablenum * 2 + tablenum - 2
Col2 = tablenum * 2 + tablenum - 1
'In this case Ranges are only used to retrieve the values for the filters therefore
'instead of using ranges just set the value directly into the corresponding variables
vDte1 = Sheets("Sheet2").Cells(1, Col1).Value2
vDte2 = Sheets("Sheet2").Cells(1, Col2).Value2
Set pt = ActiveSheet.PivotTables(comptable)
'Suggest to refresh the PivotCache
'Use this line if all PivotTables share a common PivotCache
If tablenum = 2 Then pt.PivotCache.Refresh
'Otherwise use this line instead: pt.PivotCache.Refresh
With pt.PivotFields("Maturity Date")
.ClearAllFilters
.PivotFilters.Add2 Type:=xlDateBetween, Value1:=vDte1, Value2:=vDte2
End With: Next
Application.ScreenUpdating = False
End Sub