我无法将数据字段添加到我的数据透视表VBA

时间:2017-08-20 06:43:18

标签: vba excel-vba pivot-table excel

我收到运行时错误

  

无法获取Worksheet类的PivotTables属性

当我运行以下代码时:

Sub UpdatePivot()

Dim ws As Worksheet, SrcData As String, pvtCache As PivotCache
Dim ws2 As Worksheet, NR As Long, NC As Long, ws3 As Worksheet
Dim pf As PivotField, pt As PivotTable, df As PivotField, str As String

'Set ws = ThisWorkbook.Worksheets("Lisun Data")
Set ws2 = ThisWorkbook.Worksheets("Cover")
Set ws3 = ThisWorkbook.Worksheets("Stockist")
Set pt = ws3.PivotTables("PivotTable3")
Set pt = ws3.PivotTables("PivotTable3")
With pt.PivotFields(" May-17")
    .Orientation = xlColumnField
    .Function = xlSum
    .Position = 1
End With

End Sub

我可能知道出了什么问题吗?

我事先将数据源添加到数据模型中,我不确定究竟是什么导致了错误。

2 个答案:

答案 0 :(得分:0)

尝试使用以下代码尝试捕获错误,并在代码注释中解释:

Option Explicit

Sub UpdatePivot()

Dim ws As Worksheet, SrcData As String, pvtCache As PivotCache
Dim ws2 As Worksheet, NR As Long, NC As Long, ws3 As Worksheet
Dim pf As PivotField, pt As PivotTable, df As PivotField, str As String

'Set ws = ThisWorkbook.Worksheets("Lisun Data")
Set ws2 = ThisWorkbook.Worksheets("Cover")
Set ws3 = ThisWorkbook.Worksheets("Stockist")

' 1ST: Trap the Pivot-Table object
On Error Resume Next
Set pt = ws3.PivotTables("PivotTable3")
On Error GoTo 0
If pt Is Nothing Then '<-- Pivot Table does't exist (Pivot Table renamed ?)
    MsgBox "Pivot-Table object Error!"
Else ' Pivot-Table object exists

    ' 2NDT: Trap the PivotField object
    On Error Resume Next
    Set pf = pt.PivotFields(" May-17")
    On Error GoTo 0
    If pf Is Nothing Then
        MsgBox "Pivot-Field object Error!"
    Else
        With pf
            .Orientation = xlColumnField
            .Function = xlSum
            .Position = 1
        End With
    End If
End If

End Sub

答案 1 :(得分:0)

感谢@Shai Rado提供的所有反馈,非常有价值。同样非常感谢@jeffreyweir,我录制了一个宏,并找到了我需要的答案。从数据模型添加任何数据透视表字段的代码如下:

ActiveSheet.PivotTables("PivotTable3").AddDataField ActiveSheet.PivotTables( _
        "PivotTable3").CubeFields("[Measures].[Sum of May-17]"), "Sum of May-17"