Home » excel » excel – Copying ranges from one sheet to another using variable cell references

excel – Copying ranges from one sheet to another using variable cell references

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am trying to copy one range to another via vba in excel, however it refuses to copy anything. This is my code:

Worksheets("SEARCH SHEET").Range(Cells(destination_y, 1), Cells(destination_y, 25)).Value
 = Worksheets("STOCK-INDIV").Range(Cells(currentItem_y, 1), Cells(currentItem_y, 25)).Value

and at previous point in the code I state:

currentItem_y = ActiveCell.Row

and

destination_y = ActiveCell.Row

I know the destination and current references are correct, and by doing

Worksheets("SEARCH SHEET").Range(Cells(destination_y, 1), Cells(destination_y, 25)).Select

I know that the correct cells are set to be copied and pasted to.

How to&Answers:

You need to qualify the Cells as belonging to a specific worksheet, otherwise it’s assumed to use the ActiveSheet, which is not what you want.

My preference is to use more object-oriented programming, it will be easier to do qualify the Cells portions of the Range objects. So your code :

Worksheets("SEARCH SHEET").Range(Cells(destination_y, 1), Cells(destination_y, 25)).Value
 = Worksheets("STOCK-INDIV").Range(Cells(currentItem_y, 1), Cells(currentItem_y, 25)).Value

Make sure that the values of destination_y and currentItem_y are correct (I would like to revise to avoid using ActiveCell reference), and then you can modify your code to something like:

Dim wsSearch As Worksheet
Dim wsStock As Worksheet
Dim sourceRange as Range
Dim destRange as Range

'## Define worksheet object variables
Set wsSearch = Worksheets("SEARCH SHEET")
Set wsStock = Worksheets("STOCK-INDIV")

With wsSearch
    '## Explicitly define a range object on this Worksheet
    Set destRange = .Range(.Cells(destination_y,1), .Cells(destination_y,25))
End With
With wsStock
   '## Explicitly define a range object on this Worksheet
    Set sourceRange = .Range(.Cells(currentItem_y, 1), .Cells(currentItem_y, 25))
End With

'## Transfer values from sourceRange to destRange
destRange.Value = sourceRange.Value