[英]Excel Combining/Concatenating one column based on the value of another
I apologise if this question already exists, I searched for a while but couldn't find anything. 抱歉,这个问题已经存在,我搜寻了一段时间,但找不到任何东西。
I have 2 columns in Excel and I need to concatenate the values of 1 column where the values of another are the same. 我在Excel中有2列,我需要将另一列的值相同的1列的值连接起来。 As an example I have this: 例如,我有这个:
A | B
12 | Value 1
10 | Value 2
13 | Value 3
12 | Value 4
10 | Value 5
And I would like to get out: 我想出去:
A | B
12 | Value 1, Value 4
10 | Value 2, Value 5
13 | Value 3
I have thousands of rows and ideally I would like it to create a new worksheet with the results and not destroy the existing sheet. 我有成千上万的行,理想情况下,我希望它用结果创建一个新的工作表,而不破坏现有的工作表。 There are also some blank values in column B which I would like it to ignore and not concatenate. B列中还有一些空白值,我希望它忽略而不是连接在一起。
Thanks in advance. 提前致谢。
Try this: 尝试这个:
Sub combineValues()
Dim dic As Dictionary
Dim key, val, i, p, k
Set dic = New Dictionary
For i = 1 To Worksheets(1).Range("A65536").End(xlUp).Row
key = Worksheets(1).Cells(i, 1).Value
val = Worksheets(1).Cells(i, 2).Value
If dic.Exists(key) Then
dic.Item(key) = dic.Item(key) & ", " & val
Else
dic.Add key, val
End If
Next
p = 1
For Each k In dic.Keys
Worksheets(2).Cells(p, 1) = k
Worksheets(2).Cells(p, 2) = dic.Item(k)
p = p + 1
Next
End Sub
Note that you'll have to include "Microsoft Scripting Runtime" in "Reference" in order to use Dictionary
. 请注意,您必须在“参考”中包括“ Microsoft脚本运行时”,才能使用Dictionary
。
Tested with following [Sheet 1]: 经过以下[Sheet 1]测试:
1 value 1
2 value 2
3 value 3
1 value 4
1 value 5
3 value 6
3 value 7
2 value 8
1 value 9
2 value 10
2 value 11
2 value 12
Results in following [Sheet 2]: 结果如下[表2]:
1 value 1, value 4, value 5, value 9
2 value 2, value 8, value 10, value 11, value 12
3 value 3, value 6, value 7
I have found that Passerby's answer works beautifully, but in my case, I have several columns that I run this on and in some cases there are empty cells. 我发现Passerby的答案效果很好,但就我而言,我有几列可以运行此列,并且在某些情况下,有空单元格。 To avoid getting , , , entries, I added this: 为了避免获取,,条目,我添加了以下内容:
If val <> "" Then
before 之前
dic.Item(key) = dic.Item(key) & ", " & val
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.