Turn Excel range into VBA string

前端 未结 7 1852
野性不改
野性不改 2020-11-30 11:51

I would like to turn values in given range into VBA string where original cell values are separated by any chosen column delimiter and row delimiter. Delimiters could be one

7条回答
  •  一个人的身影
    2020-11-30 12:26

    Here is a UDF that returns the desired output:

    EDIT Changed to add EOL at the end.

    Option Explicit
    Function MultiJoin(Rng As Range, Delimiter As String, EOL As String) As String
        Dim V As Variant, W As Variant
        Dim COL As Collection
        Dim I As Long, J As Long
    
    V = Rng
    Set COL = New Collection
    ReDim W(1 To UBound(V, 2))
    For I = 1 To UBound(V, 1)
        For J = 1 To UBound(V, 2)
            W(J) = V(I, J)
        Next J
        COL.Add W
    Next I
    
    ReDim V(1 To COL.Count)
    For I = 1 To COL.Count
        V(I) = Join(COL(I), Delimiter)
    Next I
    
    W = Join(V, EOL)
    MultiJoin = W & EOL
    
    End Function
    

    One could shorten the code by using WorksheetFunctions, but I would guess execution time would be slower.

    Shortened Code

    Option Explicit
    Function MultiJoin(Rng As Range, Delimiter As String, EOL As String) As String
        Dim V As Variant, W As Variant
        Dim I As Long, J As Long
    
    V = Rng
    With WorksheetFunction
    
    For I = 1 To UBound(V, 1)
        V(I, 1) = Join(.Index(V, I, 0), Delimiter)
    Next I
    MultiJoin = Join(.Transpose(.Index(V, 0, 1)), EOL) & EOL
    
    End With
    
    End Function
    

提交回复
热议问题