【问题标题】:Excel VBA: Output Distinct Values and SubtotalsExcel VBA:输出不同的值和小计
【发布时间】:2010-12-08 20:56:59
【问题描述】:

我有这种形式的数据:

Category      Source      Amount
Dues          FTW         $100
Donations     ODP         $20
Donations     IOI         $33
Dues          MMK         $124

没有排序顺序。这些类别在编译时是未知的。我希望 VBA 宏在范围内循环,输出不同值的列表,以及每个值的小计。对于上面的数据,它看起来像这样:

Category      Total Amount
Dues          $224
Donations     $55

我该怎么做?另外,有没有办法让宏在每次更新上表时运行,或者用户是否需要点击按钮?

【问题讨论】:

    标签: vba excel distinct-values


    【解决方案1】:

    您可能希望使用内置的 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
    

    该链接有多个关于如何刷新工作表/工作簿中的数据透视表的选项。

    【讨论】:

    • 我同意,数据透视表就是您所追求的
    • 如何找到数据透视表/图表的名称?
    • 右键单击数据透视表并选择数据透视表选项。这将向您显示当前名称,并允许您根据需要更改名称。
    • 我该如何做到,所以每次选择工作表时都会调用Worksheet_Activate
    • 另外,有没有办法让它更通用,比如“刷新此工作表上的所有数据透视表?”
    猜你喜欢
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    相关资源
    最近更新 更多