【问题标题】:Combining duplicate entries and adding together unique numerical data合并重复的条目并将唯一的数字数据加在一起
【发布时间】:2013-11-25 22:04:12
【问题描述】:

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

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

【问题讨论】:

    标签: excel


    【解决方案1】:

    如果您想使用代码而不是 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)
    

    戈登

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-29
      • 2013-05-20
      • 1970-01-01
      • 2015-08-05
      • 1970-01-01
      • 2015-10-11
      相关资源
      最近更新 更多