使用可变单元格引用将范围从一个表格复制到另一个表格

我试图复制一个范围通过在Excel中的VBA另一个,但它拒绝复制任何东西。 这是我的代码:

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 

并在代码的前一点我说:

 currentItem_y = ActiveCell.Row 

 destination_y = ActiveCell.Row 

我知道目的地和目前的参考是正确的,通过做

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

我知道正确的单元格被设置为复制和粘贴。

您需要将单元格限定为属于特定工作表,否则将假定使用ActiveSheet,而不是您想要的。

我的select是使用更多的面向对象的编程,那么对Range对象的Cells部分进行限定会更容易。 所以你的代码:

 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 

确保destination_ycurrentItem_y的值是正确的(我想修改以避免使用ActiveCell引用),然后你可以修改你的代码,如下所示:

 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