将分隔符添加到连接列表

我发现这个自定义Excel函数:

Function Join(source As Range, Optional delimiter As String) As String ' ' Join Macro ' Joins (concatenates) the values from an arbitrary range of cells, ' with an optional delimiter. ' 'optimized for strings ' check len is faster than checking for "" ' string Mid$ is faster than variant Mid ' nested ifs allows for short-circuit + is faster than & Dim sResult As String Dim oCell As Range For Each oCell In source.Cells If Len(oCell.Value) > 0 Then sResult = sResult + CStr(oCell.Value) + delimiter End If Next If Len(sResult) > 0 Then If Len(delimiter) > 0 Then sResult = Mid$(sResult, 1, Len(sResult) - Len(delimiter)) End If End If Join = sResult End Function 

我想调整它显示每个单元格之间的逗号它组合创build一个列表。

你发现这个UDF有一些问题:

  • 连接应该用“&”而不是“+”来完成。
  • 使用范围中的单元格比变体数组更慢,而且纯粹从VBA内部工作。 对Excel的每次调用都会产生一个小小的性能提升。
  • 如果连接正确完成,则转换为string是不理智的。
  • 应该优化连接,以便首先连接较小的部分,然后将结果添加到结果中,否则将复制两次结果以完成每个连接。
  • 名称不应该join,因为VBA具有该名称的function。
  • 因为它是一个string,所以不需要检查分隔符的LEN。 默认情况下,如果不存在,它将是LEN(0),你可以毫无顾虑地从len(result)中减去0。
  • 不是什么大不了的事情,但是检查不平等<>会比>更快一点。

这是我的版本。 默认情况下,如果您将第二个参数留空(例如:= ConcatenateRange(A1:A100)

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

它看起来已经用可选的delimiter参数来做到这一点。

就像这样调用它:

 =JOIN(A1:A100,",")