在Excel中连接2列,按元素 - 值和文本,省略空白单元格(使用vba)

时间:2016-02-13 15:04:36

标签: excel vba excel-vba concatenation

  

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,以便它逐个元素地合并两列。我希望用户手动选择每个范围(使用文本或通过指定它,因为它们不相邻)。我想要两个额外的功能:1)我希望它忽略空白单元格,2)我想保留重复的值。为了显示我想要输出的内容,我们需要第二列数据:

  

series_b   
105   
205   
  
305   
405   
505   

605   
605


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

  

,105,109,205,quick,305,199,405,brown,505,299,605,299,605


注意空白是忽略的,并保留重复项。
有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

这可能会帮助您入门:

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 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

答案 1 :(得分:0)

我修改了Alex P的代码以使其跳过空白。我通过添加if / then语句来做到这一点。这可能不是最优雅的解决方案。尽管如此,它的确有效!谢谢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