Excel VBA:从工作表名称列表制作数据透视表

时间:2013-09-26 21:57:51

标签: excel vba excel-vba pivot-table

这是一个宏的开始,它根据指定工作表中的单元格成功创建了一个数据透视表:

aray = Array("'Sheet1'!R1C5:R102C10", "'Sheet2'!R1C5:R102C10", "'Sheet3'!R1C5:R102C10", "'Sheet4'!R1C5:R102C10")

ActiveWorkbook.PivotCaches.Create(SourceType:=xlConsolidation, SourceData:= aray, _
    Version:= _
    xlPivotTableVersion15).CreatePivotTable TableDestination:= _
    "'[Filename.xlsm]sheet5'!R1C1", TableName:= _
    "RatingSumPiv", DefaultVersion:=xlPivotTableVersion15

我的问题是我不知道这些床单的名称或者有多少。它们的名称将位于名为“UnitNumbers”的范围(ListObject)中。

如何自动将工作表名称加载到数组中?

1 个答案:

答案 0 :(得分:1)

Sub Sample()
Dim loSheetNames As ListObject
Dim rngCurrentSheetName As Range
Dim toprowoflo As Long
Dim lngCurrentIndex As Long

Set loSheetNames = ActiveWorkbook.Worksheets("Sheet1").ListObjects("listob1")
toprowoflo = loSheetNames.Range.Row
ReDim aray(loSheetNames.Rows.Count)

For Each rngCurrentSheetName In loSheetNames.Range
    lngCurrentIndex = rngCurrentSheetName.Row - toprowoflo + 1
    aray(lngCurrentIndex) = rngCurrentSheetName & "!R1C5:R102C10"
Next rngCurrentSheetName

ActiveWorkbook.PivotCaches.Create(SourceType:=xlConsolidation, SourceData:=aray, _
    Version:= _
    xlPivotTableVersion15).CreatePivotTable TableDestination:= _
    "'[Filename.xlsm]sheet5'!R1C1", TableName:= _
    "RatingSumPiv", DefaultVersion:=xlPivotTableVersion15

End Sub