Luu*_*yen 1 excel vba range excel-vba
我想将多个范围复制到另一个工作簿。我有下面的代码。如何用iLastRow替换数字1000
iLastRow = Sh.Range("B" & Rows.Count).End(xlUp).Row
sh.Range("A3:AG1000, AL3:EJ1000").Select
Selection.Copy
Run Code Online (Sandbox Code Playgroud)
尝试下面的代码,并在代码中以注释的形式进行解释:
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
Run Code Online (Sandbox Code Playgroud)
另一个问题是您如何粘贴中间有间隙的合并后的重切范围。