Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select and Copy multiple ranges with VBA

Tags:

range

excel

vba

I want to copy multiple range to another workbook. I have the code below. How can I replace the number 1000 by iLastRow

iLastRow = Sh.Range("B" & Rows.Count).End(xlUp).Row
sh.Range("A3:AG1000, AL3:EJ1000").Select
Selection.Copy
like image 351
Luu nguyen Avatar asked Jan 19 '26 18:01

Luu nguyen


2 Answers

Try the code below, explanation inside the code as comments:

Option Explicit

Sub CopyMultipleRanges()

Dim iLastRow As Long
Dim sh As Worksheet
Dim MultiRng As Range

Set sh = ThisWorkbook.Worksheets("Sheet1") ' <-- change to your sheet's name
With sh
    iLastRow = .Cells(.Rows.Count, "B").End(xlUp).Row

    ' use the union to set a range combined from multiple ranges
    Set MultiRng = Union(.Range("A3:A" & iLastRow), .Range("AL3:EJ" & iLastRow))
End With

' copy the range, there's no need to select it first
MultiRng.Copy

End Sub

Another question is how you want to paste the merged reanges that have a gap in the middle.

like image 194
Shai Rado Avatar answered Jan 22 '26 13:01

Shai Rado


The Union method is a solution to this problem. but it also has its cons copy multirange test

The union range should be the same first row and last row. On the other hand, you can just select the first cell to paste. you can alway do like this. the main point here is the row number should be the same. here I synchronize both range with the same variable. in your case, change to last cell.

j=1
i = 4
Set MultiRng = Union(Range("A" & j & ":B" & i), Range("D" & j & ":E" & i))
like image 20
Duc Anh Nguyen Avatar answered Jan 22 '26 12:01

Duc Anh Nguyen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!