|
本帖最后由 爱疯 于 2013-4-19 11:32 编辑
- Sub Top5Customers()
- Dim WSD As Worksheet
- Dim WSR As Worksheet
- Dim WBN As Workbook
- Dim PTCache As PivotCache
- Dim PT As PivotTable
- Dim PRange As Range
- Dim FinalRow As Long
- Set WSD = Worksheets("PivotTable")
-
- '删除其他透视表
- For Each PT In WSD.PivotTables
- PT.TableRange2.Clear
- Next PT
- WSD.Range("J1:Z1").EntireColumn.Clear
-
- ' 定义输入数据以及数据源
- FinalRow = WSD.Cells(Application.Rows.Count, 1).End(xlUp).Row
- FinalCol = WSD.Cells(1, Application.Columns.Count). _
- End(xlToLeft).Column
- Set PRange = WSD.Cells(1, 1).Resize(FinalRow, FinalCol)
- Set PTCache = ActiveWorkbook.PivotCaches.Add(SourceType:= _
- xlDatabase, SourceData:=PRange.Address)
-
- ' 创建数据透视表
- Set PT = PTCache.CreatePivotTable(TableDestination:=WSD. _
- Cells(2, FinalCol + 2), TableName:="PivotTable1")
-
- '关闭更新
- PT.ManualUpdate = True
-
- ' 设置行列字段
- PT.AddFields RowFields:="Customer", ColumnFields:="Product"
-
- ' 设置数据字段
- With PT.PivotFields("Revenue")
- .Orientation = xlDataField
- .Function = xlSum
- .Position = 1
- .NumberFormat = "#,##0"
- .Name = "Total Revenue"
- End With
-
- ' 如果数据为空以0表示
- PT.NullString = "0"
-
- ' 根据数据排序
- PT.PivotFields("Customer").AutoSort Order:=xlDescending, _
- Field:="Total Revenue"
-
- ' 显示排名前5
- PT.PivotFields("Customer").AutoShow Type:=xlAutomatic, Range:=xlTop, _
- Count:=5, Field:="Total Revenue"
-
- PT.ManualUpdate = False
- PT.ManualUpdate = True
-
- ' 创建新的工作报表
- Set WBN = Workbooks.Add(xlWBATWorksheet)
- Set WSR = WBN.Worksheets(1)
- WSR.Name = "Report"
- ' 设置标题
- With WSR.[A1]
- .Value = "Top 5 Customers"
- .Font.Size = 14
- End With
-
- ' 复制数据
- PT.TableRange2.Offset(1, 0).Copy
- WSR.[A3].PasteSpecial Paste:=xlPasteValuesAndNumberFormats
- LastRow = WSR.Cells(Rows.Count, 1).End(xlUp).Row
- WSR.Cells(LastRow, 1).Value = "Top 5 Total"
-
- ' 返回透视表获取数据
- PT.PivotFields("Customer").Orientation = xlHidden
- PT.ManualUpdate = False
- PT.ManualUpdate = True
- PT.TableRange2.Offset(2, 0).Copy
- WSR.Cells(LastRow + 2, 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
- WSR.Cells(LastRow + 2, 1).Value = "Total Company"
-
- ' 清除透视表
- PT.TableRange2.Clear
- Set PTCache = Nothing
-
- ' 设置一下新表的格式
- WSR.Range(WSR.Range("A3"), WSR.Cells(LastRow + 2, 6)).Columns.AutoFit
- Range("A3").EntireRow.Font.Bold = True
- Range("A3").EntireRow.HorizontalAlignment = xlRight
- Range("A3").HorizontalAlignment = xlLeft
- ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$3:$G$11"), , xlYes).Name = _
- "Table1"
- ActiveSheet.ListObjects("Table1").TableStyle = "TableStyleDark5"
- Range("A2").Select
- MsgBox "CEO Report has been Created"
- End Sub
复制代码 |
|