检查PT表数据字段是否存在VBA

时间:2018-08-27 12:52:49

标签: excel vba pivot-table

enter image description here

我的代码运行得很完美……但是无论如何,它每次运行都会添加一个数据字段。我尝试用If pf.Orientation = xlDataField = True Then...("Don't add xlDataField")...测试它是否仍然存在。

我很确定我在这里遗漏了一些重要的东西,否则代码运行良好。有没有办法添加不存在的其他字段?

Sub Import()

    Dim ws As Worksheet, pvtCache As PivotCache
    Dim wsp As Worksheet
    Dim pf As PivotField, pt As PivotTable

    Set wsp = Sheets("Pivot")
    Set pt = wsp.PivotTables("PivotTable")

    ActiveWorkbook.RefreshAll

    Sheets("TP_Coois").Cells.Replace ",", "", xlPart
    Set pf = pt.PivotFields("Sales")

    If pf.Orientation = xlDataField = True Then  '***I believe here is something wrong***
        pt.PivotCache.Refresh
    Else
        With pf
            .Orientation = xlDataField
            .Function = xlSum
        End With

        pt.PivotCache.Refresh
    End If

End Sub

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

尝试从以下位置更改条件:

If pf.Orientation = xlDataField = True Then

对此:

If pf.Orientation = xlDataField Then