【发布时间】:2018-04-09 19:06:57
【问题描述】:
我有创建数据透视表并将所需的“数据透视表”添加到表中的代码。我似乎无法弄清楚的一件事是如何在“过滤器”区域下添加“数据透视字段”。
这是我的代码:
Sub CreatePivotTable()
'PURPOSE: Creates a brand new Pivot table on a new worksheet from data in the ActiveSheet
'Source: www.TheSpreadsheetGuru.com
Dim pvtSht As Worksheet
Dim summarySht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String
Dim pf As PivotField
'Determine the data range you want to pivot
SrcData = ActiveSheet.UsedRange.Address(ReferenceStyle:=xlR1C1)
'Create a new worksheet
Set pvtSht = Sheets.Add
ActiveSheet.Name = "PivotTable"
'Where do you want Pivot Table to start?
StartPvt = pvtSht.Name & "!" & pvtSht.Range("A3").Address(ReferenceStyle:=xlR1C1)
'Create Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
'Create Pivot table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvt, _
TableName:="P1")
'Insert Row Fields
With ActiveSheet.PivotTables("P1").PivotFields(" Vulnerability Name")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("P1").PivotFields(" DNS Name")
.Orientation = xlRowField
.Position = 2
End With
With ActiveSheet.PivotTables("P1").PivotFields(" Operating System")
.Orientation = xlRowField
.Position = 3
End With
With ActiveSheet.PivotTables("P1")
.AddDataField ActiveSheet.PivotTables( _
"P1").PivotFields("IP Address"), "Count of IP Addresses"
.PivotFields("IP Address").Orientation = xlRowField
End With
With Sheets("PivotTable").PivotTables("P1").PivotFields("IP Address")
.Orientation = xlRowField
.Position = 2
End With
Set pf = ActiveSheet.PivotTables("P1").PivotFields(" Vulnerability Name")
'Collapse Pivot Field
pf.ShowDetail = True
'Expand Pivot Field
pf.ShowDetail = False
'Create a new worksheet
Set summarySht = Sheets.Add
ActiveSheet.Name = "Summary"
End Sub
这是它在数据透视表上输出的内容:
这是我需要它输出的内容(注意 Risk Rating 在 Filters 下):
这是需要在工作表上显示的内容:
【问题讨论】: