2013-12-16 132 views
1

我写在VBA这段代码创建一个数据透视表(从宏把它转换,acctually ...),并且它不工作创建在VBA透视表,在Excel 2013

Dim wsTarget As Worksheet 
Dim rngSource As Range 
Dim pc As PivotCache 
Dim pt As PivotTable 
Dim field As PivotField 

Application.ScreenUpdating = False 

Set rngSource = Summary.Range("A1").CurrentRegion 
Set wsTarget = PivotTable 

wsTarget.Select 
For Each pt In wsTarget.PivotTables 
    pt.Delete 
Next pt 

Set pc = ThisWorkbook.PivotCaches.Create(xlDatabase, rngSource, xlPivotTableVersion15) 
Set pt = pc.CreatePivotTable(wsTarget.Range("A3"), "PivotTable1", , xlPivotTableVersion15) 

Set field = wsTarget.PivotTables("PivotTable1").PivotFields("A") 
field.Orientation = xlColumnField 
field.Position = 1 
field.LayoutBlankLine = True 

Set field = wsTarget.PivotTables("PivotTable1").PivotFields("B") 
field.Orientation = xlRowField 
field.Position = 1 

Set field = wsTarget.PivotTables("PivotTable1").PivotFields("TOTAL") 
Set field = wsTarget.PivotTables("PivotTable1").AddDataField(field, "Sum of TOTAL", xlSum) 
field.NumberFormat = "_ $ * #,##0.00_ " 

Application.ScreenUpdating = True 

该代码不断崩溃在“设置电脑”行,我不知道为什么... 尝试使用Google搜索,并且所有的结果都与我的代码相同... 重要的细节 - 我正在与Excel 2013年,也许是因为那... 会感谢我能得到的任何帮助 - 谢谢!

回答

0

尝试this..i认为你是直接引用的表名..

Set rngSource = Sheets("Summary").Range("A1").CurrentRegion 
Set wsTarget = sheets("PivotTable") 
+0

我做到了,但它仍然无法正常工作..它好像rngSource不能得到整个表的值.. 有另一种方式插入表格范围到变量? 谢谢! – Bramat

+0

将附件上传到某处。把链接发给我..我会努力工作 –

0

试试这个:

Dim lrow As Long 
Dim lcol As Long 
Dim rngSource As Range 

lrow = ActiveSheet.Cells(Application.Rows.Count, 1).End(xlUp).Row 
lcol = ActiveSheet.Cells(1, Application.Columns.Count).End(xlToLeft).Column 

Set rngSource = ActiveSheet.Cells(1, 1).Resize(lrow, lcol)