数据透视表& VBA

时间:2016-10-10 13:57:38

标签: excel vba excel-vba

所以我有这个数据透视表,我可以在其中对“工厂名称”进行排序。我可以简单地硬编码功能,说“Plant26”,“Plant12”等,以了解可以分类的植物名称。但是,是否有不同的方法来访问所有这些名称并将它们放在一个数组中,而不是遍历几千行并在该列中查找名称的差异,然后将它们附加到数组中?

示例:

    For i = 5 to lastrow
    Name = Cells(i, "A").Value
    If 
    'in array
    Else
    'add in array
    End If
    next i

然而有更快的方法吗?是否有可能获得可以分类并将它们放入数组的植物名称?这是一个伪示例..

   With Worksheets("sheet2").PivotTables(1)
    For i = 1 To .PivotFields("Plant Name").Count
        MsgBox .PivotFields(i).Name
        'Add to array
    Next
End With

2 个答案:

答案 0 :(得分:1)

这会让您开始,它会在PivotItems"工厂名称"中显示所有PivotField

注意:建议避免使用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

答案 1 :(得分:0)

这将列出植物的名称,并在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