2

I'm using a code to change one pivot field of just one pivot according to the value of a cell (the cell contain text, is not a reference to another cell). The strangest thing is that it works for almost all the values I have but not with all of them...

The code is the following:

Private Sub Worksheet_Change(ByVal Target As Range)
If Not Application.Intersect(Target, Sheets("Sheet2").Range("D1")) Is Nothing Then
Sheets("Sheet2").PivotTables("PivotTable1").PivotFields("Field1"). _
ClearAllFilters
Sheets("Sheet2").PivotTables("PivotTable1").PivotFields("Field1").CurrentPage _
= Sheets("Sheet2").Range("D1").Value
End If
End Sub

the debug says the problem is the following line

Sheets("Sheet2").PivotTables("PivotTable1").PivotFields("Field1").CurrentPage _=      Sheets("Sheet2").Range("D1").Value

and the error says : " Run-time error '1004' Application-defined or object-defined error".

Can someone please help me? Thank you very much!

p.s. the value of the cell containing the text that is used to change the pivot field is changed by another macro that takes the value from a pivot so the value are existing and the format is the same for all the values so I can't figure out what is the problem...

4

1 回答 1

0

Not exactly an expert, but after some research I'd suggest you try out this code:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim pt As PivotTable

If Not Intersect(Target(1, 1), Range("D1")) Is Nothing Then
    Set pt = Me.PivotTables(1)
    With pt
        .RefreshTable
        .PivotFields("Field1").CurrentPage = Range("D1").Text
    End With
End If
End Sub

It probably slows down the process a bit!

于 2012-12-14T15:03:34.530 回答