数据透视表和VBA
所以我有这个数据透视表,我可以在“植物名称”上sorting。 我可以简单地在“Plant26”,“Plant12”等硬编码function中知道可以sorting的植物名称。 然而,是否有不同的方式来访问所有这些名称,并将它们放在一个数组中,而不是遍历数千行,并find该列中名称的差异,然后将它们附加到数组?
例:
For i = 5 to lastrow Name = Cells(i, "A").Value If 'in array Else 'add in array End If next i
但是有没有更快的方法? 是否有可能获得这些可以sorting的植物名称,并将它们放入一个数组? 这是一个伪示例
With Worksheets("sheet2").PivotTables(1) For i = 1 To .PivotFields("Plant Name").Count MsgBox .PivotFields(i).Name 'Add to array Next End With
这会让你开始,它会显示在PivotField
“工厂名称”中的所有PivotItems
。
注意 :build议避免使用ActiveSheet
。
选项显式
Sub GetAllPlantNamefromPivot() Dim PvtItm As PivotItem Dim PvtFld As PivotField Dim PlantArr() As Variant Dim count As Long Set PvtFld = ActiveSheet.PivotTables("PivotTable1").PivotFields("Plant Name") ' reset Plant Name Array count count = 0 For Each PvtItm In PvtFld.PivotItems ReDim Preserve PlantArr(0 To count) PlantArr(count) = PvtItm count = count + 1 Next PvtItm End Sub
这将列出植物的名称并在Sheet3
显示结果数组:
Sub test_Amasian21() Dim A() ReDim A(1 To 1) Dim i As Double With Sheets("sheet2").PivotTables(1).PivotFields("Plant Name") For i = 1 To .PivotItems.Count A(UBound(A)) = .PivotItems(i).Name ReDim Preserve A(LBound(A) To UBound(A) + 1) Next i End With ReDim Preserve A(LBound(A) To UBound(A) - 1) Sheets("sheet3").Range("A1").Resize(UBound(A), 1).Value = A End Sub