1

我正在尝试通过 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

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

4

1 回答 1

3

您需要将单元格限定为属于特定工作表,否则假定使用 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
于 2013-11-11T16:07:47.630 回答