Concatenate multiple ranges using vba

前端 未结 9 1312
臣服心动
臣服心动 2020-12-03 03:51

I have a number of ranges to concatenate independently and put the values of the concatenated ranges into different cells.

I want to:
concatenate values in Range

9条回答
  •  醉酒成梦
    2020-12-03 04:34

    Here is my ConcatenateRange. It allows you to add a seperator if you please. It is optimized to handle large ranges since it works by dumping the data in a variant array and working with it within VBA.

    You would use it like this:

    =ConcatenateRange(A1:A10)
    

    The code:

    Function ConcatenateRange(ByVal cell_range As range, _
                        Optional ByVal seperator As String) As String
    
    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
    

提交回复
热议问题