繁体   English   中英

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

[英]Copying ranges from one sheet to another using variable cell references

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

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

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

我更喜欢使用更多面向对象的编程,更容易对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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM