类型不匹配错误 - 通过Excel VBA进行数据透视表过滤

时间:2011-07-18 21:10:25

标签: excel-vba filtering pivot-table type-mismatch vba

我一直在尝试使用输入框来使用数据透视过滤器。我从http://www.ozgrid.com/VBA/hide-pivot-fields.htm窃取了大部分代码,并且一直在申请我的电子表格并不断收到我无法弄清楚的类型不匹配错误。该示例是为数字而构建的,我需要对文本进行过滤。

错误查找器在Evaluate函数上停止,但两个变量都定义为文本,因此我认为它必须是Org变量。非常感谢任何建议 - 代码如下。

Sub HideByCriteria() Dim pt As PivotTable,pi As PivotItem Dim Org As String Dim strCri As String Dim bHide As Boolean Dim xlCalc As XlCalculation

Set pt = Sheets("Req Posting Status").PivotTables("PivotTable1")

    strCri = InputBox("Enter Organization" _
        & Chr(13) & "Valid Criteria Examples:" _
        & Chr(13) & "HCS-CT for all HCS-CT orgs" _
        & Chr(13) & "or CKS for any org that contains CKS", "HIDE AGE")

 If strCri = vbNullString Then Exit Sub
 strCri = Trim(strCri)

 pt.ManualUpdate = True
 With Application
        xlCalc = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
 End With

'On Error GoTo NonValidCriteria:

    For Each pi In pt.PivotFields("Organization").PivotItems
        Org = pi
        bHide = Evaluate(Org & strCri)
        pi.Visible = bHide
    Next pi

pt.ManualUpdate = False
With Application
        .Calculation = xlCalc
        .ScreenUpdating = True
 End With

退出子

1 个答案:

答案 0 :(得分:0)

以下代码在Excel 2003中进行了测试,效果非常好。如果您有任何其他问题,请告诉我。上面发布的代码中有很多冗余代码。

  

KISS - 保持简单愚蠢。

Public Sub HideMacro()
Dim pi As PivotItem
Dim critera As String

critera = LCase$(Trim$(InputBox("Do you want to see HCS-CT or CKS?", "Critera", "CKS")))

If critera = vbNullString Then
    MsgBox "Cancelled Filter", vbInformation + vbOKOnly, "Information"
    Exit Sub
ElseIf critera <> "hcs-ct" And critera <> "cks" Then
    MsgBox "Invalid entry. Please try again.", vbCritical + vbOKOnly, "Invalid Entry"
    Exit Sub
End If

With Sheet4.PivotTables(1)
    .ManualUpdate = True
    For Each pi In .PivotFields("Orginization").PivotItems
        pi.Visible = (LCase$(pi.Value) = critera) 'Hides other value and shows wanted value.
    Next
    .ManualUpdate = False
End With

End Sub