Home » excel » vba – Copying multiple ranges and concatenating them in Excel

vba – Copying multiple ranges and concatenating them in Excel

Posted by: admin May 14, 2020 Leave a comment


My Excel sheet has multiple used ranges. I want to copy each range value and concatenate them. What I did is

Set tempRange = Union(SrcWkb.Worksheets("mysheet").Range("F1:H1"), SrcWkb.Worksheets("mysheet").Range("I1:J1"), SrcWkb.Worksheets("NWP").Range("K1:L1"))

For Each eachRange In tempRange
  tempString = tempString & eachRange & "/"
  MsgBox tempString
Next eachRange

I want to copy the value in merged cells F1:H1 and concatenate a “/” and value from I1:J1 (also merged) and K1 to L1. However, Excel throws “subscript out of range” error. How could I achieve this?


How to&Answers:

It is not quite clear from your original post what output you need. Here is one option which may help you get started:

Sub ConcatRanges()
    Dim rangeOne As Range, rangeTwo As Range, rangeAll As Range, cl As Range, str As String

    Set rangeOne = Worksheets("mysheet").Range("I27:K27")
    Set rangeTwo = Worksheets("mysheet").Range("L27:N27")
    Set rangeAll = Union(rangeOne, rangeTwo)

    For Each cl In rangeAll
        str = str & cl & " / "
    Next cl

    Debug.Print str //Output: 1 / 2 / 3 / 4 / 5 / 6 /
End Sub

Updated Post

Dealing with merged ranges can be tricky. For example, the merged range F1:H1 has value 36M. To access the value you have to refer to the first cell in the merged range. Example:

Sub MergedRangeDemo()
    Dim rng As Range, cl As Range
    Set rng = ActiveSheet.Range("F1:H1")

    For Each cl In rng
        Debug.Print cl.Value, cl.Address
    Next cl

    //Output: 36M    $F$1  <-- Only first cell contains the value
    //               $G$1
    //               $H$1
End Sub

Given this you can concatenate the values by using the rowindex (1) of the range:

Sub ConcatRangesUpdated()
    Dim rangeOne As Range, rangeTwo As Range, rangeThree As Range, str As String

    Set rangeOne = ActiveSheet.Range("F1:H1")
    Set rangeTwo = ActiveSheet.Range("I1:J1")
    Set rangeThree = ActiveSheet.Range("K1:L1")

    str = rangeOne(1) & " / " & rangeTwo(1) & " / " & rangeThree(1)

    Debug.Print str 'Output: 36M / 40M / 36M
End Sub


It appears that you want to concatenate I27 and L27 with a forward slash between and put the results on a different worksheet. This example does just that: concatenates I27 & L27, J27 & M27, K27 & N27 and puts the results in cells A27:C27 on the destination sheet. Note that the formula uses R1C1 notation with relative column positions; adjust as necessary.

Sub ConcatCells()
Dim sSource As String
sSource = "'" & SrcWkb.Worksheets("mysheet").Name & "'!"
DstWks1.Range("A27:C27").FormulaR1C1 = "=" & sSource & "RC[8] & " _
    & Chr$(34) & "/" & Chr$(34) & " & " & sSource & "RC[11]"
End Sub