使用带有Excel的VBA无效的过程调用或参数

时间:2015-08-31 19:08:07

标签: excel vba excel-vba

我一直收到这个错误: 运行时错误'5':

无效的过程调用或参数:

我正在学习VBA ......&是的,在我试图提出这个问题之前,我已经在这里搜索了答案。首先,我尝试在TableDestination中添加单引号(但是表单名称中没有空格),&然后我试着刷新我做的桌子,没有bueno。我还确保数据透视表名称是唯一的,以前没有使用过,最后我遇到了一个删除Sheets.Add语句并离开TableDestination:=“”的解决方案。这有效,但是当我生成报告时,它会在excel数据之前插入数据透视表,我想要反过来,我确定我做错了很简单,但我似乎无法找到我的内容需要

Sub PostProcessing()
 Dim MainWorksheet As Worksheet

 Set MainWorksheet = ActiveWorkbook.Worksheets("Query1")

 Dim pt     As PivotTable
 Dim pf     As PivotField
 Dim pi     As PivotItem
 Dim pc     As PivotCache
 Dim ws     As Worksheet

 With ActiveWorkbook
    For Each pc In .PivotCaches
        pc.MissingItemsLimit = xlMissingItemsNone
    Next pc
 End With

 'Create a pivot table on page Two

 Sheets.Add After:=Sheets(Sheets.Count)

  ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
  SourceData:= "Query1!R1C7:R90C8", _
  Version:=xlPivotTableVersion14).CreatePivotTable _
  TableDestination:="Sheet1!R1C1", TableName:= "PTCtable"

 With ActiveSheet.PivotTables("PTCtable")'
    With .PivotFields("Assigned To")
       'Set the Row Field
       .Orientation = xlRowField
       .Position = 1
    End With

    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.ChartType = xlColumnClustered
 End With

End Sub

2 个答案:

答案 0 :(得分:0)

您的问题与工作表的名称无关,您只是不以正确的方式调用函数。 您想创建一个数据透视表,而您没有为其指定任何名称:您错过了等式的左侧部分。以下必须有效。

    pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase,         
    SourceData:="Query1!R1C7:R90C8", Version:=xlPivotTableVersion14)
    pt = pc.CreatePivotTable(TableDestination:="Sheet1!R1C1",TableName:="PTCtable")

如果没有,请尝试:

    Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase,         
    SourceData:="Query1!R1C7:R90C8", Version:=xlPivotTableVersion14)
    Set pt = pc.CreatePivotTable(TableDestination:="Sheet1!R1C1",TableName:="PTCtable")

答案 1 :(得分:0)

所以我使用了一些@jamesC建议,而是使用了范围代替表格数据,&让它运作起来。我确定某些代码可能不是最有效的,因为我对这种语言还很新,但下面就是我所做的:(接受任何改进建议)

 Dim pt          As PivotTable
 Dim pf          As PivotField
 Dim pi          As PivotItem
 Dim pc          As PivotCache

  With ActiveWorkbook
    For Each pc In .PivotCaches
        pc.MissingItemsLimit = xlMissingItemsNone
    Next pc
  End With

 'Create a pivot table on page Two

  ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)

  ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
  SourceData:="Query1!R1C7:R90C8", _
  Version:=xlPivotTableVersion14).CreatePivotTable _
  TableDestination:=Sheets(2).Range("A1:B1"), TableName:="PTCtable"


With Sheets(2).PivotTables("PTCtable") '
    With .PivotFields("Assigned To")
       'Set the Row Field
       .Orientation = xlRowField
       .Position = 1
    End With

Sheets(2).Select

ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered

End With