用户窗体列表框中的数据透视表字段 - Excel vba

时间:2016-11-18 20:57:05

标签: excel-vba pivot-table vba excel

过去两周,我一直在寻找解决方案。

目的是在userform Listbox中查看和编辑数据透视表中的数据。

我有一个包含四列的数据透视表:

Code (number) | Name (text) | Card Number (number) | SDCard (number). 

按代码列排序。

在我的用户格式Listbox中,我有以下代码:

Private Sub UserForm_Initialize()

Dim pvtTable As PivotTable
Dim pvtField As PivotField
Dim lngIndex As Long

Set pvtTable = Worksheets("Store").PivotTables(1)
Set pvtField = pvtTable.PivotFields("Code")

With pvtTable.PivotCache
    .MissingItemsLimit = xlMissingItemsNone
    .Refresh
End With

pvtTable.PivotFields("Code").ClearAllFilters
pvtTable.PivotFields("Code").AutoSort Order:=xlAscending, Field:="Code"

For lngIndex = 1 To pvtField.PivotItems.Count
    UserForm1.listBox1.AddItem pvtField.PivotItems(lngIndex).Name
Next

End Sub

我可以看到字段" Code" Listbox中的项目,但没有其他内容。

1 个答案:

答案 0 :(得分:0)

以下代码包含2个Sub个,Sub UserForm_Initialize之一和Sub ListBox1_Change中的另一个。整个代码都在User_Form模块中。

(解释在代码注释内)

Option Explicit

Dim pvtTable As PivotTable
Dim pvtField As PivotField
Dim pvtItem  As PivotItem


Private Sub ListBox1_Change()

' this code runs once hte user changes the selection of the items inside the user_form Listbox1

Dim i As Integer

' loop through all records in Listbox ans check which one is selected
For i = 0 To ListBox1.ListCount - 1
    If ListBox1.Selected(i) Then
        ' if current item is selected in Listbox >> make current Pivot Items visible in Pivot table
        pvtField.PivotItems(ListBox1.List(i)).Visible = True
    Else
        ' if current item is not selected in Listbox >> hide current Pivot in Pivot table
        pvtField.PivotItems(ListBox1.List(i)).Visible = False
    End If
Next i

End Sub


Private Sub UserForm_Initialize()

' this code runs on User_from intialize process
' it add items to the Listbox with all PivotItems in PivotField "Code"

Set pvtTable = Worksheets("Store").PivotTables(1)
Set pvtField = pvtTable.PivotFields("Code")

With pvtTable.PivotCache
    .MissingItemsLimit = xlMissingItemsNone
    .Refresh
End With

With pvtField
    .ClearAllFilters
    .AutoSort Order:=xlAscending, Field:="Code"

    ' loop through all PivotItems in PivotField "Code" and add them to ListBox1
    For Each pvtItem In .PivotItems
        UserForm1.ListBox1.AddItem pvtItem.Name
    Next pvtItem
End With

End Sub