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

时间:2013-11-11 15:19:14

标签: excel vba excel-vba range excel-2013

我试图通过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

我知道正确的单元格已设置为复制并粘贴到。

1 个答案:

答案 0 :(得分:3)

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

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

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
相关问题