0

コードに問題があります。あるシートのセルを取得し、別のピボット シートのデータをフィルター処理するコードをアクティブにしようとしています。値が存在しない場合、エラーがあることを示すメッセージ ボックスがあります。私の問題は、値が true の場合に、msgbox に「値がピボットに存在しません」と表示したいことです。「if」が false の場合、データをフィルタリングする必要がありますが、機能しません。コードがあります:

Sub MM()
    Sheets("sheets1").Select
    Selection.Copy
    Sheets("pivot").Select
    Range("C1").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveSheet.PivotTables("pivottable1").PivotFields("filter WBS").ClearAllFilters
    ActiveSheet.PivotTables("pivottable1").PivotCache.Refresh
    If Not IsError(ActiveSheet.PivotTables("pivottable1").PivotFields("filter WBS").CurrentPage = Range("c1").Value) Then
        MsgBox ("the value dosen't exists in the pivot")
         Sheets("sheets1").Select
    Else
        ActiveSheet.PivotTables("pivottable1").PivotFields("filter WBS").CurrentPage = Range("c1").Value
    End If
End Sub

喜んでお手伝いします!

4

2 に答える 2

0

選択したセルの内容に応じてピボットをフィルター処理するかどうかは完全にはわかりませんが、ここに私の提案があります。多くの値でピボットをフィルタリングする方法があることを指摘するために、1 つの値に対してのみフィルタを実行することを望んでいたと思いますか? また、フィルターをピボットに追加する方法は、すべてのフィールド値をループして、表示または非表示に設定することです。

Sub testi2()
    'Bit waisty way to do it, you could just make a variable to hold the value -
    Dim myValue As Variant
    myValue = ActiveCell.Value
    'Sheets("sheets1").Select
    'Selection.Copy
    Sheets("pivot").Select
    'Range("C1").Select
    'Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    'Your choise tough, if you really need to copy the value to the cell C1 then by all 
    'means do, but you should still send the value to variable for code will be easier 
    'to be handled and clearer to read.
    'Here you could also clear all past filters for the pivot if needed. 
    'I won't encourage to but if there are other filters present exept
    'what is in filterWBS field, the code will run into an error. 

    Dim pItem As PivotItem
    Dim ifFound As Boolean
    ifFound = False

    'loop trough the pivotfieldvalues to see if match exists, pivot tables have a need for at least one visible value.
    For Each pItem In ActiveSheet.PivotTables("pivottable1").PivotFields("filter WBS").PivotItems

        'if data exists then ifFound value will be set to true
        If pItem = myValue Then
            ifFound = True
        End If
    Next

    'based on the if value found set fields visible or hidden
    If ifFound = True Then
        For Each pItem In ActiveSheet.PivotTables("pivottable1").PivotFields("filter WBS").PivotItems
            If pItem <> myValue Then
                pItem.Visible = False
            Else
                pItem.Visible = True
            End If
        Next
    'if the value was not present show the message box
    Else
        MsgBox ("the value doesn't exists in the pivot")
        'You could in this case clear the filter
    End If
End Sub
于 2014-04-08T12:53:49.123 に答える