我正在通过VBA创建一个简单的数据透视表。我不知道我的代码有什么问题。我的代码运行没有错误,但结果不同。您能告诉我代码中的问题在哪里吗?
Sub CreatePivotTable()
Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String
'Determine the data range you want to pivot
SrcData = ActiveSheet.Name & "!" & Range("A1:B53821").Address(ReferenceStyle:=xlR1C1)
'Create a new worksheet
Set sht = Sheets.Add
'Where do you want Pivot Table to start?
StartPvt = sht.Name & "!" & sht.Range("A1").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:="PivotTable1")
pvt.PivotFields("Module").Orientation = xlRowField
pvt.PivotFields("KW").Orientation = xlColumnField
pvt.AddDataField pvt.PivotFields("Module"), "Anzahl von Module", xlCount
pvt.PivotFields("Module").PivotFilters.Add Type:=xlTopCount, DataField:=pvt.PivotFields("Anzahl von Module"), Value1:=12
End Sub
如果我手动进行操作,这就是我得到的结果,这也是我最后想要的结果。
我的代码给了我这个结果。哪有错
最佳答案
我认为您的问题在于您的初始范围很小,只有两列(A,B)和最后几行代码
'Determine the data range you want to pivot
SrcData = ActiveSheet.Name & "!" & Range("A1:B53821").Address(ReferenceStyle:=xlR1C1)
假设您在A列中有您的名字,请调用Module,而B列是KW(带数字)(模块的KW/h)
'Create Pivot table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable(TableDestination:=StartPvt, TableName:="PivotTableTest")
pvt.AddDataField pvt.PivotFields("Module"), "Num Module", xlCount
pvt.PivotFields("Module").Orientation = xlColumnField ' not xlRowField
pvt.PivotFields("KW").Orientation = xlRowField ' not xlColumnField
您不需要最后一行。
关于Excel通过VBA创建数据透视表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31732871/