0

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

我想转

  • 附属公司
  • 中心
  • 直流
  • 特许经营
  • 总部

进入:附属 > 中心 > DC > 特许经营 > 总部

这是我当前的代码

此代码有效,但它并不优雅且难以扩展到更多列表项

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

这是一些屏幕截图

4

2 回答 2

1

这是我的 VBA 解决方案版本,得到了很好的评价:

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

它与其他答案类似,但在速度和效率方面存在一些根本差异,例如使用变体数组。

于 2013-01-30T06:56:34.900 回答
1

我喜欢使用以下 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
于 2013-01-29T23:15:43.320 回答