简体   繁体   English

如何按类别对行值求和

[英]How to sum row values by category

So I have got the following table in Excel for example (it actually has 100+ rows): 因此,我在Excel中获得了下表(例如,实际上有100多个行):

Alfa     10
Beta     5
Alfa     10
Beta     5
Gama     15

What I would like to do is SUM values by the name (category) using VBA Macro, so I can display it somewhere in the Sheet like this: 我想使用VBA宏按名称(类别)对SUM值进行显示,因此我可以将其显示在工作表的某处,如下所示:

AlfaTotal     20
BetaTotal     10
GamaTotal     15

I have tried using For Each function but am not able to get to the values. 我尝试使用For Each函数,但无法获取这些值。 Any help would be much appreciated. 任何帮助将非常感激。

Using a dictionary is a common method. 使用字典是一种常见的方法。 The below handles blanks in range, also if only 1 item present. 如果仅存在一项,则以下内容将处理范围内的空白。 It doesn't need an .Exists test as simply adds to any existing value by direct access. 它不需要.Exists测试,因为只需通过直接访问即可添加任何现有值。 Also, writes arrays of keys, items out in one go. 此外,一次性写入键数组和项。

Option Explicit
Public Sub GetTotals()
    Dim dict As Object, arr(), i As Long, lastRow As Long
    Set dict = CreateObject("Scripting.Dictionary")
    With ThisWorkbook.Worksheets("Sheet1")       '<==source data
        lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        Select Case lastRow
        Case 1
            ReDim arr(1, 1): arr(1, 1) = .Range("A1:B1").Value
        Case Else
            arr = .Range("A1:B" & lastRow).Value
        End Select
    End With

    For i = LBound(arr, 1) To UBound(arr, 1)
        If Not IsEmpty(arr(i, 1)) Then
            dict(arr(i, 1)) = dict(arr(i, 1)) + arr(i, 2)
        End If
    Next
    With ThisWorkbook.Worksheets("Sheet2")
        .Range("A1").Resize(dict.Count, 1) = Application.WorksheetFunction.Transpose(dict.keys)
        .Range("B1").Resize(dict.Count, 1) = Application.WorksheetFunction.Transpose(dict.Items)
    End With
End Sub

Results: 结果:

数据

If you don't know how many categories you'll have before trying to sum them, something like this could be a solution: 如果在尝试对类别进行汇总之前不知道要拥有多少个类别,则可以使用以下解决方案:

Option Explicit

Sub test()
    Dim d As Object
    Set d = CreateObject("Scripting.Dictionary")

    Dim s As String, key_value As String
    Dim v As Variant
    Dim num As Long

    Dim r As Range, c As Range
    Set r = Sheet1.Range(Sheet1.Range("A2"), Sheet1.Range("A" & Sheet1.Rows.Count).End(xlUp))

    For Each c In r
        key_value = CStr(c)
        num = CLng(c.Offset(0, 1))

        If d.Exists(key_value) Then
            d(key_value) = d(key_value) + num
        Else
            d.Add Key:=key_value, Item:=num
        End If
    Next c

    For Each v In d
        s = s & CStr(v) & vbTab & CStr(d(v)) & vbLf
    Next v

    MsgBox prompt:=s, Title:="Summation", Buttons:=vbInformation
End Sub

If you know what categories you'll have in advance, just making some sumif formulas based on those would probably be simpler. 如果您事先知道要使用哪些类别,则仅基于这些类别创建一些sumif公式可能会更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 仅当它们与查找中的类别ID相匹配时,才如何对excel中的值求和 - How to sum values in excel only if they match a category id in a lookup 如何对每个类别求和 - How to Sum per category 如何根据同一行中的其他值对同一列中的值求和 - How to sum values in the same column based on other values in the same row 对同一类别下的多个值求和 - Sum multiple values under the same category 如果行的值在Excel中包含特定值,如何求和常数? - How to sum constants if the values of a row contian a specific value in excel? 如何在Excel中用基于列的查找中的查找值求和? - How to sum a row in Excel with lookup values from a column based lookup? (VBA)如何删除重复的行并将相应的值求和到右列? - (VBA) How to delete dupicate row and sum corresponding values to right columns? 如何在跳过某些值的同时连续计算总小时数? - How to sum total hours in a row while skipping certain values? 如何将一行和下一行的值求和,并将它们放在一列中 - how do I sum values from a row and the next row, and place them in a column 如果两张纸的行和列之间匹配,如果发现第三张纸的复印值,并且同一类别下有多个复印纸,则求和 - Match between row and column from two sheets, if found copy value from the third and if more than one under same category sum up the values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM