我正在尝试使用动态范围在新闻报道上创建数据透视表,但收到错误消息:
运行时错误:13 类型不匹配
用Google搜索错误,根据我的理解,代码包含的数据类型不正确,但我无法弄清楚错误在哪里:
使用Excel 2016。
Sub EEE()
Dim PrevSheet As Worksheet
Set PrevSheet = ActiveSheet
Sheets.Add.Name = "Pivottable"
PrevSheet.Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:=ActiveSheet.UsedRange, _
Version:=xlPivotTableVersion15).CreatePivotTable _
TableDestination:="Pivottable!R3C1", _
TableName:="PivotTable1", _
DefaultVersion:=xlPivotTableVersion15
Sheets("Pivottable").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Faculty")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("NPS")
.Orientation = xlColumnField
.Position = 1
End With
End Sub
修改后的代码 - 工作
Sub EEE()
Dim rng As Range
Dim pc As PivotCache
Dim pt As PivotTable
Dim ws As Worksheet
Set rng = ActiveSheet.Range("A1").CurrentRegion
Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabaseSourceData:=rng.Address)
Set ws = ActiveWorkbook.Worksheets.Add
ws.Name = "NewSheet"
Set pt = pc.CreatePivotTable(TableDestination:=Range("A3"),TableName:="pvttbl")
With pt
.PivotFields("Faculty").Orientation = xlRowField
ActiveSheet.PivotTables("pvttbl").AddDataField ActiveSheet.PivotTable "pvttbl").PivotFields("NPS"), "Count of NPS", xlCount
.PivotFields("NPS").Orientation = xlColumnField
End With
End Sub
答案 0 :(得分:3)
您没有说明哪条线路出错。但是有几个可能的罪魁祸首。
第(def data
{:tag :eSearchResult,
:attrs {},
:content
[{:tag :Count, :attrs {}, :content '("16")}
{:tag :RetMax, :attrs {}, :content '("16")}
{:tag :RetStart, :attrs {}, :content '("0")}
{:tag :IdList,
:attrs {},
:content
[{:tag :Id, :attrs {}, :content '("28911150")}
{:tag :Id, :attrs {}, :content '("28899394")}
{:tag :Id, :attrs {}, :content '("24740865")}]}]})
(defn tag
"Build a predicate function to check for a certain :tag"
[tag-value]
(fn [e] (= tag-value (get e :tag))))
(use 'com.rpl.specter)
; select, ALL etc is from specter; this defines a path down to the data
(select [:content ALL (tag :IdList) :content ALL (tag :Id) :content FIRST] data)
;; => ["28911150" "28899394" "24740865"]
行说“嘿,从活动工作表上找到的所有中创建数据透视表”。不是个好主意。使用数据所在的确切范围。选择存在数据块的单元格并使用CurrentRegion,例如
SourceData:=ActiveSheet.UsedRange
...甚至更好,将SourceData转换为代码中较早的Excel Table又名ListObject,并引用ListObject:
SourceData:= Activesheet.Range("A1").CurrentRegion
如果您尝试多次运行它并且您没有删除上次创建的名为“数据透视表”的工作表,您的代码也会失败。
以下是我编写代码的方法:
SourceData:= "Table1"