以下是可以用于将 Sheet2 的 A 列作为数据源创建数据透视表并计数的 VBA 代码:

Sub CreatePivotTable()

Dim wsData As Worksheet
Dim wsPivot As Worksheet
Dim pvtCache As PivotCache
Dim pvtTable As PivotTable
Dim lastRow As Long

' 设置数据源工作表和数据透视表工作表
Set wsData = ThisWorkbook.Sheets('Sheet2')
Set wsPivot = ThisWorkbook.Sheets('Sheet1')

' 找到数据源的最后一行
lastRow = wsData.Cells(Rows.Count, "A").End(xlUp).Row

' 设置数据透视表缓存
Set pvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=wsData.Range("A1:A" & lastRow))

' 在数据透视表工作表上创建数据透视表
Set pvtTable = wsPivot.PivotTables.Add(PivotCache:=pvtCache, TableDestination:=wsPivot.Range("A1"), TableName:="PivotTable1")

' 将 '数据' 字段添加到行区域
With pvtTable.PivotFields('数据')
    .Orientation = xlRowField
    .Position = 1
End With

' 将 '数据' 字段添加到值区域并计数
With pvtTable.PivotFields('数据')
    .Orientation = xlDataField
    .Function = xlCount
    .Position = 1
    .NumberFormat = "0"
    .Name = "Count"
End With

End Sub

请注意,此代码假定 Sheet2 中的数据源列标题为 '数据'。如果标题不同,请将代码中的 '数据' 更改为正确的标题。此外,此代码将在 Sheet1 上创建名为 'PivotTable1' 的数据透视表。如果需要,可以更改代码中的表名和目标单元格。

Excel VBA 代码:创建数据透视表并计数

原文地址: https://www.cveoy.top/t/topic/njCt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录