Copying a Range of Cells in Excel VBA
To copy a range of cells in Excel VBA, you can use the Range object’s Copy method. This method allows you to copy the selected cells to another location within the same worksheet or to a different worksheet in the same workbook.
Here’s an example of how to copy a range of cells:
Sub CopyRange()
Dim sourceRange As Range
Dim destinationRange As Range
' Set the source range (cells to copy)
Set sourceRange = Worksheets("Sheet1").Range("A1:D10")
' Set the destination range (where to paste)
Set destinationRange = Worksheets("Sheet2").Range("A1")
' Copy the source range to the destination range
sourceRange.Copy destinationRange
End Sub
In this example, we define two range variables: sourceRange
and destinationRange
. The sourceRange
variable represents the range of cells that we want to copy, which is A1 to D10 in the worksheet named “Sheet1”. The destinationRange
variable represents the location where we want to paste the copied cells, which is cell A1 in the worksheet named “Sheet2”.
Finally, we use the Copy
method of the sourceRange
object and specify the destinationRange
as the parameter. This will copy the values, formats, and formulas (if any) from the source range to the destination range.
Note that you can also use the Cut
method instead of Copy
if you want to move the cells instead of copying them.