【发布时间】:2015-08-07 07:59:23
【问题描述】:
我有两列代表 1:many 关系。我需要将其减少到 1:1 的关系,其中列 B 中的许多由逗号连接。数据如下:
邮政编码邻居 10001 10010 10001 10011 10001 10016 10001 10018 10001 10119 10001 10199 10003 10012这是我希望输出的样子:
邮政编码邻居 10001 10010、10011、10012、10016、10018、10019、10199有 9000 条记录,所以我需要运行一个循环直到记录结束。
现在确定如何执行此操作。
我想通了,谢谢大家。代码分享如下:
Sub Concatenate()
Dim oldValue As String
Dim newValue As String
Dim result As String
Dim counter As Integer
oldValue = ""
newValue = ""
result = ""
counter = 1
For i = 2 To 9401
newValue = Worksheets("data").Cells(i, 1)
If (oldValue <> newValue) Then
Worksheets("result").Cells(counter, 1).NumberFormat = "@"
Worksheets("result").Cells(counter, 2).NumberFormat = "@"
Worksheets("result").Cells(counter, 1) = oldValue
Worksheets("result").Cells(counter, 2) = result
counter = counter + 1
result = ""
End If
If (result = "") Then
result = Worksheets("data").Cells(i, 2)
Else
result = result + "," + Worksheets("data").Cells(i, 2)
End If
oldValue = newValue
Next i
End Sub
【问题讨论】:
-
对不起,这是一个糟糕的例子,但希望这个想法能得到普及
-
我可以给你答案,但我希望你先尝试。这是一种方法。这是一个VBA方法。
1使用集合从列表中获取唯一的邮政编码2循环遍历唯一的集合,然后在内部循环中,遍历 Col A。对于每个匹配项,连接值3输出到新工作表 -
@SiddharthRout:或者字典。在 15,000 条记录上进行了测试,它在 0.23 秒内相当快。
-
@BK201:
Collection/Dict/Array更快:) -
几周前我已经回答了一个类似的问题。你应该看看这里link!还。实际上,您只需要该示例中的 A 和 C 列