在Excel中逐个元素地连接两个列 – 值和文本,省略空白单元格(使用vba)

series_a (注意有空行)

99


199
棕色

299
299

vba模块“ConcatUniq”连接来自一列的值和文本,省略任何空白单元格和重复项。这里是“ConcatUniq”。

Function ConcatUniq(ByRef rng As Range, ByVal myJoin As String) As String Dim r As Range Static dic As Object If dic Is Nothing Then Set dic = CreateObject("Scripting.Dictionary") For Each r In rng dic(r.Value) = Empty Next ConcatUniq = Join$(dic.keys, myJoin) dic.RemoveAll End Function 

所以ConcatUniq这样做到了series_a [ConcatUniq(series_a,“,”)]:

99,快,199,棕色,299

(请注意,最后一项被忽略)
我试图修改ConcatUniq,以便它逐个元素地合并两列 。 我希望用户手动select每个范围(无论是与文本或指定它,因为他们不会相邻)。 我想要两个额外的function:1)我希望它忽略空白单元格,2)我想保留重复值。 为了显示我想要的结果,我们需要第二列数据:

series_b
105
205

305
405
505

605
605

这是我想要这个新的函数Concat2Series(series_a,series_b,“,”)输出的方式:

The,105,99,205,quick,305,199,405,brown,505,299,605,299,605

注意空白被忽略,重复被保留。
有人可以帮我弄这个吗?

这可能会帮助你开始:

 Sub ConCatTwoColumns() Dim colA As Range, colB As Range, rw As Integer, res As String Set colA = Range("A1:A6") Set colB = Range("B1:B6") For rw = 1 To colA.Rows.Count res = res & colA(rw) & ", " & colB(rw) & IIf(rw = colA.Rows.Count, vbNullString, ", ") Next rw Debug.Print res '~~> The, 105, 99, 205, quick, 305, 199 brown, 405, brown, 505, 199, 605 End Sub 

作为一个function,它只是简单的:

 Function ConCatTwoColumns(colA As Range, colB As Range) as String Dim rw As Integer, res As String For rw = 1 To colA.Rows.Count res = res & colA(rw) & ", " & colB(rw) & IIf(rw = colA.Rows.Count, vbNullString, ", ") Next rw ConCatTwoColumns = res End Function 

我修改了Alex P的代码,以避免空白。 我通过添加if / then语句来做到这一点。 这可能不是最优雅的解决scheme。 尽pipe如此,它的工作! 感谢Alex P! :

 Function ConCatTwoColumnsSkipBlanks(colA As Range, colB As Range) As String Dim rw As Integer, res As String For rw = 1 To colA.Rows.Count If IsEmpty(colA(rw)) = True Then If IsEmpty(colB(rw)) = True Then 'if both are empty res = res Else 'if only B has data res = res & colB(rw) & IIf(rw = colA.Rows.Count, vbNullString, ", ") End If End If If IsEmpty(colA(rw)) = False Then If IsEmpty(colB(rw)) = True Then 'if only A has data res = res & colA(rw) & IIf(rw = colA.Rows.Count, vbNullString, ", ") Else ' if both have data res = res & colA(rw) & ", " & colB(rw) & IIf(rw = colA.Rows.Count, vbNullString, ", ") End If End If Next rw ConCatTwoColumnsSkipBlanks = res End Function