【发布时间】:2019-03-21 01:20:09
【问题描述】:
我有一个如下所示的表格,基于黄色突出显示的列,我需要对绿色突出显示的列求和。
预期输出在这里:
我已经使用下面的代码完成了……
Sub test()
lrow = ActiveSheet.Cells(ActiveSheet.Cells.Rows.Count, 1).End(xlUp).Row
Set Rng = Range("A2:A" & lrow)
For Each cell In Rng
If Not IsEmpty(cell) Then
a = cell
b = cell.Offset(0, 1)
c = cell.Offset(0, 5)
r = cell.Row
cnt = Application.WorksheetFunction.CountIf(Rng, cell)
d = 0
For i = 1 To cnt
If Cells(r + i, 1) = a And Cells(r + i, 2) = b And Cells(r + i, 6) Then
Cells(r, 7) = Cells(r + i, 7) + Cells(r, 7)
Cells(r, 8) = Cells(r + i, 8) + Cells(r, 8)
d = d + 1
End If
Next
If d > 0 Then Range(Cells(r + 1, 1).Address, Cells(r + d, 1).Address).EntireRow.Delete
End If
Next
End Sub
我想使用脚本字典来完成,这对我来说是新的。由于我是初学者,我无法修改以下网络中的示例代码!
从here得到它
Sub MG02Sep59()
Dim Rng As Range, Dn As Range, n As Long, nRng As Range
Set Rng = Range(Range("A2"), Range("A" & Rows.Count).End(xlUp))
With CreateObject("scripting.dictionary")
.CompareMode = vbTextCompare
For Each Dn In Rng
If Not .Exists(Dn.Value) Then
.Add Dn.Value, Dn
Else
If nRng Is Nothing Then Set nRng = Dn Else Set nRng = Union(nRng, Dn)
.Item(Dn.Value).Offset(, 3) = .Item(Dn.Value).Offset(, 3) + Dn.Offset(, 3)
End If
Next
If Not nRng Is Nothing Then nRng.EntireRow.Delete
End With
End Sub
谁能帮帮我?如果可能的话,附上一些注释。
【问题讨论】:
-
考虑使用数据透视表。
-
@jsheeran,我需要使用 VBA 来完成。谢谢!
-
@Linga 那么请在您的问题中更具体一些。你在哪里得到错误?你的代码有什么问题?你在哪里遇到困难?只是发布您的代码并希望我们为您修复它不太可能在 Stack Overflow 上工作(请参阅How to Ask)。