我正在尝试编写一个宏,该宏遍历工作簿中的所有表,然后以" TableName [#All]"的形式添加每个表的名称。到阵列。
请参阅下面的不完整代码
Sub NewShopPage()
'
' Macro that creates a duplicate sheet from a hidden template
' searches for every table in the workbook and then adds them to the
' PivotTableWizard.
'
Dim NewShop As Variant
NewShop = InputBox("What Shop are you creating a new estimate sheet for? (example: Shop 18)")
NewShop = Replace(NewShop, " ", "_")
Sheets("CE_Template").Copy After:=Sheets("Project Estimator")
ActiveSheet.Name = NewShop
ActiveSheet.ListObjects(1).Name = NewShop
Sheets("Project Estimator").Select
ActiveSheet.ListObjects(1).Select
Dim MyArray As Variant
'HELP NEEDED HERE:
'For each [Table] in [workbook]
' Add TableName + "[#All]" to MyArray
'Next
ActiveSheet.PivotTableWizard SourceType:=xlConsolidation, SourceData:=MyArray
End Sub
我只得出结论它必须以这种方式运行,因为如果用户添加工作表然后删除它,则数据透视表错误会出错。
我不确定每次都会这样做会删除数据透视表的格式。
答案 0 :(得分:0)
Dim tbl As ListObject
For Each tbl In ActiveSheet.ListObjects
'Do stuff to tbl here
Next tbl
此外,如果您打算使用很多桌子,我会推荐这个网站。 http://www.thespreadsheetguru.com/blog/2014/6/20/the-vba-guide-to-listobject-excel-tables
答案 1 :(得分:0)
答案是:
Dim MyArray() As String
Dim ArraySize As Integer
Dim ws As Worksheet
Dim Tbl As ListObject
ArraySize = 0
ReDim MyArray(0 To 0)
For Each ws In ActiveWorkbook.Worksheets
For Each Tbl In ws.ListObjects
ReDim Preserve MyArray(ArraySize) As String
MyArray(UBound(MyArray)) = Tbl.Name & "[#All]"
ArraySize = ArraySize + 1
Next Tbl
Next ws