使用 VBA 在 Excel 中创建数据透视表时键入不匹配错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8450450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 14:40:55  来源:igfitidea点击:

Type mismatch error when creating a pivot table in Excel with VBA

excelvbapivot-table

提问by JP D

I'm trying to put a macro together that will make a simple pivot table using the data from an active worksheet. When I try to run it, I receive a type mismatch error. When I start the debugger, the first section is highlighted: ActiveWorkbook.PivotCaches through xlPivotTableVersion10. Initially, the TableDestination was blank and I thought that might be the problem, but after adding a destination I still get the same error.

我正在尝试将一个宏放在一起,该宏将使用活动工作表中的数据制作一个简单的数据透视表。当我尝试运行它时,我收到一个类型不匹配错误。当我启动调试器时,第一部分突出显示:ActiveWorkbook.PivotCaches 到 xlPivotTableVersion10。最初,TableDestination 是空白的,我认为这可能是问题所在,但在添加目的地后,我仍然遇到相同的错误。

ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, _
SourceData:=ActiveSheet.UsedRange).CreatePivotTable TableDestination:="Sheet1!R3C1", _
TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion10

ActiveSheet.PivotTableWizard TableDestination:=ActiveSheet.Cells(1, 1)

With ActiveSheet.PivotTables("PivotTable1").PivotFields("Program Name")
    .Orientation = xlColumnField
    .Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
    "PivotTable1").PivotFields("Dollars Awarded"), "Sum of Dollars Awarded", xlSum
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Dept Head")
    .Orientation = xlRowField
    .Position = 1
End With

采纳答案by Tim Williams

This worked for me (XL2007):

这对我有用(XL2007):

Sub Tester()

    With ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, _
        SourceData:=ActiveSheet.UsedRange)

        .CreatePivotTable TableDestination:="Sheet1!R3C1", _
        TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion10

    End With

    With Sheet1.PivotTables("PivotTable1")
        .PivotFields("Dept Head").Orientation = xlColumnField
        .PivotFields("Program Name").Orientation = xlRowField
        .AddDataField .PivotFields("Cost"), "Sum of cost", xlSum
    End With

End Sub

Make sure you don't already have an existing conflicting pivot cache/table.

确保您还没有现有的冲突数据透视缓存/表。