以下是可以用于将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 SHEET2的数据a列作为数据源然后在sheet1里面做成数据透视表然后计数 vba代码

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

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