2013-12-16 167 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)