|
- Sub PivotTable()
- Dim ws As Worksheet
- Dim pt As PivotTable
- Dim pf As PivotField
- Dim pi As PivotItem
- Dim rng As Range
- Dim lastRow As Long
- Dim lastCol As Long
- Dim i As Long
- Dim j As Long
- Dim keyword As String
- '设置关键字
- keyword = "a"
- '获取当前工作表
- Set ws = ActiveSheet
- '获取数据范围
- lastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
- lastCol = ws.Cells(1, Columns.Count).End(xlToLeft).Column
- Set rng = ws.Range("A1", ws.Cells(lastRow, lastCol))
- '创建数据透视表
- Set pt = ws.PivotTableWizard(TableDestination:=ws.Cells(lastRow + 2, 1), _
- TableName:="PivotTable")
- '设置行字段
- Set pf = pt.PivotFields("所有")
- pf.Orientation = xlRowField
- '设置列字段
- Set pf = pt.PivotFields("关键字")
- pf.Orientation = xlColumnField
- '设置值字段
- Set pf = pt.PivotFields("值")
- pf.Orientation = xlDataField
- pf.Function = xlSum
- pf.NumberFormat = "#,##0"
- '筛选关键字
- For i = 1 To pf.PivotItems.Count
- Set pi = pf.PivotItems(i)
- If pi.Name <> keyword Then
- pi.Visible = False
- End If
- Next i
- '自动调整列宽
- ws.Columns.AutoFit
- End Sub
复制代码 |
|