如果不是空的话,如何连接多个列

时间:2014-12-29 13:17:12

标签: excel vba excel-vba excel-2007

我想用9来将9列的值连接成1列价值之间。问题是某些列对于某些行是空的,因此使用= CONCATENATE()函数非常难看,因为您需要检查= if(A2 ="&#34 ;; .. 。)对于9列中的每一列。

是否有更智能的方法在excel中组合这些多列,只使用其中包含值的单元格?也许使用VBA?

举例来说,表格看起来像:

| A    | B    | C | D     | E       | F | G   | H   | I   |
|------+------+---+-------+---------+---+-----+-----+-----|
| lion | king |   |       | animals |   |     |     | dog |
| lion |      |   | queen |         |   | cat | jet |     |

1.行的输出应该是:" lion | king | animals | dog"对于2.行:"狮子|女王|猫|喷射"

有人可以帮忙吗?

非常感谢!!

3 个答案:

答案 0 :(得分:5)

您可以使用简单的UDF:

Function MyConcat(ConcatArea As Range) As String
  For Each x In ConcatArea: xx = IIf(x = "", xx & "", xx & x & "|"): Next
  MyConcat = Left(xx, Len(xx) - 1)
End Function

将上述代码复制到标准代码模块中,并在工作表中使用,如下所示:

=MyConcat(A1:J1)

在没有使用凌乱的SUBSTITUTE / IF函数的情况下,使用工作表公式实际上没有这样做。


编辑(OP请求)

删除重复项:

Function MyConcat(ConcatArea As Range) As String
  For Each x In ConcatArea: xx = IIf(x = "" Or InStr(1, xx, x & "|") > 0, xx & "", xx & x & "|"): Next
  MyConcat = Left(xx, Len(xx) - 1)
End Function

答案 1 :(得分:3)

Public Function ConcatItNoDuplicities(ByVal cellsToConcat As Range) As String
    ConcatItNoDuplicities = ""
    If cellsToConcat Is Nothing Then Exit Function
    Dim oneCell As Range
    Dim result As String
    For Each oneCell In cellsToConcat.Cells
        Dim cellValue As String
        cellValue = Trim(oneCell.value)
        If cellValue <> "" Then
            If InStr(1, result, cellValue, vbTextCompare) = 0 Then _
                result = result & cellValue & "|"
        End If
    Next oneCell
    If Len(result) > 0 Then _
        result = Left(result, Len(result) - 1)
    ConcatItNoDuplicities = result
End Function

enter image description here

答案 2 :(得分:0)

您可以使用这样的UDF(根据自己的需要调整):

Function Conc(v As Variant, Optional ByVal sDelim As String = "") As String
    Dim vLoop As Variant
    If IsArray(v) Or TypeName(v) = "Range" Then
        For Each vLoop In v
            If Conc = "" Then
                Conc = vLoop
            ElseIf vLoop <> "" Then
                Conc = Conc & sDelim & vLoop
            End If
        Next vLoop
    Else
        Conc = CStr(v)
    End If
End Function