如何连接多个列,如果不是空的
我想用9连接9列的值到1列 值之间。 问题在于某些行的某些列是空的,因此使用= CONCATENATE()函数非常难看,因为您需要为每个行检查= if(A2 =“”; …) 9列。
有没有更聪明的方法来结合在Excel中的这些多列,只使用有价值的单元格? 也许使用VBA?
为了举例说明,工作表看起来像这样:
| A | B | C | D | E | F | G | H | I | |------+------+---+-------+---------+---+-----+-----+-----| | lion | king | | | animals | | | | dog | | lion | | | queen | | | cat | jet | |
1.行的输出应该是:“狮子|动物|狗”和2.线:“狮子|猫”
有人可以帮忙吗?
非常感谢!
你可以使用一个简单的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
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
你可以像这样使用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