组合重复条目并将唯一数字数据相加

时间:2013-11-25 22:04:13

标签: excel

我有两列数据。我想在第一列中找到所有类似的值,然后将相关第二列中的数值相加。随机顺序有数百个值。

当遇到第一列中的类似值时,NickSlash编写了一些关于如何在第二列中组合文本值的代码。我是一个完整的新手。基本上NickSlash编写的代码非常棒,除了我需要在第二列中添加数值。 NickSlash回答的问题可以在这里找到。 Combining duplicate entries with unique data in Excel

NickSlash编写的代码如下所示,我希望这样的代码与电子表格中的公式相对。

Option Explicit

Sub Main()
Dim Source As Worksheet: Set Source = ThisWorkbook.Worksheets("Sheet1")
Dim Destination As Worksheet: Set Destination = ThisWorkbook.Worksheets("Sheet2")

Dim Records As Object: Set Records = CreateObject("Scripting.Dictionary")

Dim Data As Variant
Dim Index As Long
Dim Row As Integer: Row = 1

Data = Source.Range("A1", "B" & Source.Rows(Source.UsedRange.Rows.Count).Row).Value2

For Index = LBound(Data, 1) To UBound(Data, 1)
    If Records.Exists(Data(Index, 1)) Then
        Destination.Cells(Records(Data(Index, 1)), 2).Value2 = Destination.Cells(Records(Data(Index, 1)), 2).Value2 & ", " & Data(Index, 2)
    Else
        Records.Add Data(Index, 1), Row
        Destination.Cells(Row, 1).Value2 = Data(Index, 1)
        Destination.Cells(Row, 2).Value2 = Data(Index, 2)
        Row = Row + 1
    End If
Next Index

Set Records = Nothing

End Sub

1 个答案:

答案 0 :(得分:0)

如果你想用代码而不是sumif来做这件事,你应该只需要替换这一行

Destination.Cells(Records(Data(Index, 1)), 2).Value2 = Destination.Cells(Records(Data(Index, 1)), 2).Value2 & ", " & Data(Index, 2)

    Destination.Cells(Records(Data(Index, 1)), 2).Value2 = Destination.Cells(Records(Data(Index, 1)), 2).Value2 + Data(Index, 2)

戈登