我是 Excel 宏的新手。我正在學習使用宏為專案創建資料透視表。最終我會使用 Power Automate 讓它每天都自動運行。
首先,我嘗試在 Excel 中使用 Record Macro 來弄清楚如何創建資料透視表,然后我得到了下面的代碼。
Range("A1:W37").Select
Application.CutCopyMode = False
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Sheet1!R1C1:R37C23", Version:=8).CreatePivotTable TableDestination:= _
"Sheet19!R3C1", TableName:="PivotTable2", DefaultVersion:=8
Sheets("Sheet19").Select
Cells(3, 1).Select
我無法弄清楚的問題是如何確保我可以選擇作業表中的所有單元格并將它們存盤到變數中。然后我可以將該變數放在 SourceData:= _ 之后(這意味著該變數將替換代碼“Sheet1!R1C1:R37C23”)。我在互聯網上搜索可以通過以下代碼選擇所有包含資料的單元格:
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
試圖谷歌它,但幾個小時后沒有運氣。有什么建議嗎?
uj5u.com熱心網友回復:
你可以這樣做:
Sub Tester()
Dim ws As Worksheet, wsPT As Worksheet, rngData As Range, wb As Workbook
Dim pc As PivotCache, pt As PivotTable
Set wb = ActiveWorkbook 'or some other specific workbook
Set ws = wb.Worksheets(1) 'or some other specific sheet
'same as selecting A1 and pressing Ctrl A
Set rngData = ws.Range("A1").CurrentRegion
Set wsPT = wb.Worksheets.Add() 'get a reference to the new sheet
'create pivot cache
Set pc = wb.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:=rngData, Version:=8)
'create pivot table
Set pt = pc.CreatePivotTable(TableDestination:=wsPT.Range("A3"), _
TableName:="PivotTable2", DefaultVersion:=8)
'work with `pt`....
End Sub
如果將資料透視快取和資料透視表的創建分成單獨的步驟,您將獲得更多控制權。
uj5u.com熱心網友回復:
您可以從此 URL 找到一大堆 Excel-VBA-Pivot 資源。
https://www.contextures.com/
此外,請考慮在單擊需要執行的步驟時錄制宏,并從宏錄制器生成的代碼中學習。我保證你會從這些型別的練習中學到很多東西。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/519610.html
標籤:擅长vba
上一篇:單元格范圍在公式中自動移動
