[英]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.