set tsbc = thisworkbook.pivotcaches.create(xldatabase,sheets(1).range("A1").currentregion,4)

创建一个数据透视表的缓存空间,sheets(1).range("A1").currentregion要生成透视表的数据区域(注此数据区域需要有表头);后一个参数”4“,意思不详,默认这样表述。

set tsb = tsbc.createpivotTable(sheets(2).[a1],"数据透视表1",true,4)

将透视表放在sheets(2).[a1]处,"数据透视表1"是透视表的名称,自由取名(有多个透视表时不要相同)。后二个参数意思不详,默认这样表述。


with tsb

.pivotfields("表头名二").orientation=xlcolumnfield 添加为”列项“

.pivotfields("表头名一").orientation=xlrowfield 添加为”行项“

.pivotfields("表头名三").orientation=xldatafield 添加为”值项“

.pivotfields("表头名一").autosort 2, "求和项:表头名三"

按"求和项:表头名三" ,对”表头名一“的 进行 降序排序。(1 为升序)

.RowAxislayout xlTabularRow //经典透视布局

end with

第二种写法

with tsb


.addfields "一","二" 先是”行项“逗号之后是”列项“

添加多个的写法.addfields array("一","四"),array("二","三")

.adddatafield .pivotfields("表头名三"), , xlsum (最后参数指求和)

end with

完整语句:

dim tsbc as pivotcache,tsb as pivottable

set tsbc = thisworkbook.pivotcaches.create(xldatabase,sheets(1).range("A1").currentregion,4)

set tsb = tsbc.createpivotTable(sheets(2).[a1],"数据透视表1",true,4)

with tsb

.addfields "一","二"

.adddatafield .pivotfields("表头名三"), , xlsum

.pivotfields("一").autosort 2, "求和项:三"

.RowAxislayout xlTabularRow

end with