Excel VBA:输出不同值和小计
-
05-07-2019 - |
题
我有这种形式的数据:
Category Source Amount
Dues FTW $100
Donations ODP $20
Donations IOI $33
Dues MMK $124
没有排序顺序。这些类别在编译时是未知的。我想要一个 VBA 宏循环遍历范围,输出不同值的列表,以及每个值的小计。对于上面的数据,它看起来像这样:
Category Total Amount
Dues $224
Donations $55
我怎样才能做到这一点?另外,有没有办法让宏在每次更新上表时运行,或者用户是否需要单击按钮?
解决方案
您可能需要使用内置的 Excel 功能来执行此操作。如果您有很多值需要循环,则循环可能会花费很长时间并且会出现问题。
类似下面的内容可能会帮助您开始创建数据透视表(从 http://www.ozgrid.com/News/pivot-tables.htm)
Sub MakeTable()
Dim Pt As PivotTable
Dim strField As String
'Pass heading to a String variable
strField = Selection.Cells(1, 1).Text
'Name the list range
Range(Selection, Selection.End(xlDown)).Name = "Items"
'Create the Pivot Table based off our named list range.
'TableDestination:="" will force it onto a new sheet
ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, _
SourceData:="=Items").CreatePivotTable TableDestination:="", _
TableName:="ItemList"
'Set a Pivot Table variable to our new Pivot Table
Set Pt = ActiveSheet.PivotTables("ItemList")
'Place the Pivot Table to Start from A3 on the new sheet
ActiveSheet.PivotTableWizard TableDestination:=Cells(3, 1)
'Move the list heading to the Row Field
Pt.AddFields RowFields:=strField
'Move the list heading to the Data Field
Pt.PivotFields(strField).Orientation = xlDataField
End Sub
这是用于小计的(尽管我更喜欢数据透视表)http://msdn.microsoft.com/en-us/library/aa213577(office.11).aspx
编辑:我重读并有以下想法。在单独的工作表上设置数据透视表(不使用任何代码),然后将以下代码放在具有数据透视表的工作表上,以便每次选择工作表时该表都会更新。
Private Sub Worksheet_Activate()
Dim pt As PivotTable
'change "MiPivot" to the name of your pivot table
Set pt = ActiveSheet.PivotTables("MyPivot")
pt.RefreshTable
End Sub
编辑#2在表上刷新所有枢轴表http://www.ozgrid.com/VBA/pivot-table-refresh.htm
Private Sub Worksheet_Activate()
Dim pt As PivotTable
For Each pt In ActiveSheet.PivotTables
pt.RefreshTable
Next pt
End Sub
该链接有多个关于如何刷新工作表/工作簿中的数据透视表的选项。
不隶属于 StackOverflow