简体   繁体   中英

Hide pivot table items using excel VBA

I want to check the Colum A and Column E value and then collapse the Pivot table based on the values.

myfile.Sheets(3).Select
Dim dd As Range
Dim ee As Range
Dim ff As String
     For Each ee In myfile.Sheets(3).Range("E1:E20000")
     For Each dd In myfile.Sheets(3).Range("A1:A20000")
         With ee
            If Left(dd.Value, 1) = "F" And ee.Value = "0.00" Or ee.Value = "(0.00)" Then ff = Left(dd.Value, 10)
            ActiveSheet.PivotTables(1).PivotFields("Ref 1").PivotItems(ff).ShowDetail = False
        End With
     Next
     Next

I think this where the error comes up. Specially with the variable ff.

ActiveSheet.PivotTables(1).PivotFields("Ref 1").PivotItems(ff).ShowDetail = False

Try putting your string in Quotes. So like

ActiveSheet.PivotTables(1).PivotFields("Ref 1").PivotItems(""" & ff & """).ShowDetail = False

Also if FF does not get set it still trys to collapse the pivot. So try putting that in an if statement so if FF <> "" then .....showdetails = false

EDIT updated code which should work.

myFile.Sheets(3).Select
Dim i As Long
Dim ff As String

For i = 5 To 5000
    If Left(ActiveSheet.Range("A" & i).Value, 1) = "F" And ActiveSheet.Range("E" & i).Value = "0" Then
        ff = Left(ActiveSheet.Range("A" & i).Value, 10)
        If ff <> "" Then
            For j = 1 To ActiveSheet.PivotTables("PivotTable1").PivotFields("Ref 1").PivotItems.Count
                If ActiveSheet.PivotTables("PivotTable1").PivotFields("Ref 1").PivotItems(j).Name = ff Then
                    ActiveSheet.PivotTables("PivotTable1").PivotFields("Ref 1").PivotItems(j).ShowDetail = False
                End If
            Next
        End If

    End If
Next i

The pivotItems is looking for an Index. So I have looped through all of them to see if FF matches the name of them. If it does it will hide the details.

Let me know if this works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM