过去两周,我一直在寻找解决方案。
目的是在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
中的项目,但没有其他内容。
答案 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