Why is this PivotItem.Visible call throwing a TypeMismatch error?

后端 未结 4 1434
失恋的感觉
失恋的感觉 2021-01-26 19:22

This is baffling us. I have a standard pivot table with a report filter on it that allows multiple selection of items. I can get the selected items in the report filter with:

4条回答
  •  盖世英雄少女心
    2021-01-26 19:46

    I wrote a post some time back on this at http://dailydoseofexcel.com/archives/2013/11/09/a-date-with-pivotitems/

    What's weird is that this seems to affect some machines and not others, and also some versions and not others.

    I wrote a small test routine that sets up a pivot with two items in it - one a date, and one a number - and that then tries to set the .visible status to true...first with the number format set to a date format, and then with the number format set to 'General'

    On my system, I get an error on 2010 when the format is set to General, but no error when set to a date format. But strangely when I run the same code on Excel 2013, I get no error whatsoever. So it appears to be fixed.

    A commenter at the Daily Dose post said it wasn't an issue for him in either version.

    So maybe it's a weird combo of version and region.

    Here's my test code, if anyone else is interested in seeing what it does on their box:

    Sub Test()
    
    Dim pf As PivotField
    Dim pc As PivotCache
    Dim pt As PivotTable
    Dim pi As PivotItem
    Dim rng As Range
    
    [A1].Value = "Data"
    [A2].Value = "=TODAY()"
    [A3].Value = "=VALUE(TODAY())"
    
    Set rng = Cells(ActiveSheet.UsedRange.Row, ActiveSheet.UsedRange.Columns.Count + ActiveSheet.UsedRange.Column + 1)
    
    Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=[A1].CurrentRegion)
    Set pt = pc.CreatePivotTable(TableDestination:=rng)
    Set pf = ActiveSheet.PivotTables(1).PivotFields(1)
    
    
    pf.NumberFormat = "d/mm/yyyy"
    For Each pi In pf.PivotItems
    pi.Visible = True
    Next pi
    
    pf.NumberFormat = "General"
    For Each pi In pf.PivotItems
    pi.Visible = True 'Code errors out for me here using Excel 2010
    Next pi
    
    End Sub
    

提交回复
热议问题