vba透视表汇总,并整理表格
时间: 2023-05-11 20:04:59 浏览: 282
可以使用 VBA 编写代码来实现透视表的汇总和整理表格的功能。以下是一个简单的示例代码:
Sub PivotTableSummary()
'定义变量
Dim pt As PivotTable
Dim ws As Worksheet
'设置工作表
Set ws = ActiveWorkbook.Worksheets("Sheet1")
'创建透视表
Set pt = ws.PivotTableWizard(TableDestination:=ws.Range("H1"), _
TableName:="PivotTable1", _
RowGrand:=True, _
ColumnGrand:=True, _
SaveData:=True, _
HasAutoFormat:=True, _
AutoPage:=True, _
Reserved:=True, _
BackgroundQuery:=False, _
OptimizeCache:=True, _
PageFieldOrder:=xlDownThenOver, _
PageFieldWrapCount:=0, _
ReadData:=True)
'设置透视表字段
With pt.PivotFields("Region")
.Orientation = xlRowField
.Position = 1
End With
With pt.PivotFields("Product")
.Orientation = xlRowField
.Position = 2
End With
With pt.PivotFields("Sales")
.Orientation = xlDataField
.Function = xlSum
.NumberFormat = "#,##0.00"
End With
'整理表格
ws.Range("H1").Select
ws.Range(Selection, Selection.End(xlToRight)).Select
ws.Range(Selection, Selection.End(xlDown)).Select
ws.Sort.SortFields.Clear
ws.Sort.SortFields.Add Key:=Range("H2"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ws.Sort.SortFields.Add Key:=Range("I2"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ws.Sort
.SetRange Range("H1:I11")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
这个代码可以在 Excel 中使用,它会创建一个透视表,并对表格进行排序和整理。你可以根据自己的需求修改代码中的参数和字段。
阅读全文
相关推荐
















