在VBA中创建数据透视表时出错

时间:2016-11-22 08:45:28

标签: vba excel-vba excel

当我尝试运行下面的代码时出现错误。任何人都可以解释为什么我在代码试图创建枢轴时在最后一部分得到错误?

错误说:“无效的过程调用或参数”在我设置pvt的最后一部分

Private Sub CommandButton1_Click()

Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String

For Each PT In Sheet5.PivotTables
    PT.TableRange2.Clear
Next PT

'Determine the data range you want to pivot
  SrcData = ActiveSheet.Name & "!" & Range("B7:D10").Address(ReferenceStyle:=xlR1C1)

'Where do you want Pivot Table to start?
  StartPvt = Sheet5.Name & "!" & Sheet5.Range("B12").Address(ReferenceStyle:=xlR1C1)

'Create Pivot Cache from Source Data
  Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
    SourceType:=xlDatabase, _
    SourceData:=SrcData)

MsgBox StartPvt & "_" & SrcData

'Create Pivot table from Pivot Cache
    Set pvt = pvtCache.CreatePivotTable( _
    TableDestination:=StartPvt, _
    TableName:="TestPivotTable")

End Sub

1 个答案:

答案 0 :(得分:2)

我认为您的代码很难处理SrcDataStartPvt作为字符串存储,因为它需要一个范围。 这与您的完全相同,但它将范围存储为Range并仅在需要时将它们转换为字符串。

Private Sub CommandButton1_Click()

    Dim sht As Worksheet
    Dim pvtCache As PivotCache
    Dim pvt As PivotTable
    Dim SrcData As Range, StartPvt As Range
    Dim PT As Variant

    For Each PT In Sheet5.PivotTables
        PT.TableRange2.Clear
    Next PT

    'Determine the data range you want to pivot
      Set SrcData = ActiveSheet.Range("B7:D10")

    'Where do you want Pivot Table to start?
      Set StartPvt = Sheet5.Range("B12")

    'Create Pivot Cache from Source Data
      Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
        SourceType:=xlDatabase, _
        SourceData:=SrcData.Address)

    MsgBox StartPvt.Parent.Name & "!" & StartPvt.Address(ReferenceStyle:=xlR1C1) & "_" & _
           SrcData.Parent.Name & "!" & SrcData.Address(ReferenceStyle:=xlR1C1)

    'Create Pivot table from Pivot Cache
        Set pvt = pvtCache.CreatePivotTable( _
        TableDestination:=StartPvt, _
        TableName:="TestPivotTable")

End Sub