【问题标题】:Add delimiter to concatenated list将分隔符添加到串联列表
【发布时间】:2011-08-29 20:18:50
【问题描述】:

我找到了这个自定义 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

我想对其进行调整以在它组合以创建列表的每个单元格之间显示一个逗号。

【问题讨论】:

  • 我不会将该函数命名为“Join”,因为已经有一个具有该名称的 VBA 函数,它在数组上执行相同的工作(但不是在 Ranges 上)。

标签: vba excel user-defined-functions


【解决方案1】:

您发现的 UDF 存在一些问题:

  • 应使用“&”而不是“+”进行连接。
  • 使用范围内的单元格比使用变体数组要慢,并且完全在 VBA 内部工作。对 Excel 的每次调用都会对性能产生小幅影响,可能会累加。
  • 如果连接正确,则不需要强制转换为字符串。
  • 应优化串联,以便先连接较小的部分,然后将其添加到结果中,否则将复制两次结果以执行每个串联。
  • 名称不应为 Join,因为 VBA 具有该名称的功能。
  • 应该不需要检查 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

【讨论】:

  • @Issun 哪个会更快:Right$(newString, (Len(newString) - Len(seperator))) 或类似:Mid$(newString ,Len(分隔符)+1)?我使用后者,因为代码更短,但我从未检查过速度。
  • 在当前计算机上差异可能可以忽略不计,但 Right() 比 Mid() 快。
【解决方案2】:

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

只要这样称呼它:

=JOIN(A1:A100,",")

【讨论】:

    猜你喜欢
    • 2018-07-15
    • 2010-10-01
    • 1970-01-01
    • 2020-04-01
    • 2020-11-01
    • 2015-11-22
    • 1970-01-01
    • 2013-08-20
    • 2018-10-20
    相关资源
    最近更新 更多