VBA copy and paste only work if I activate the sheet

眉间皱痕 提交于 2020-06-27 18:32:06

问题


I am copying some ranges between sheets and I don't know why it only works when I activate the sheet before I copy or paste them. This works:

s.Activate
s.Range(Cells(2, 8), Cells(lrow, 8)).Copy
d.Activate
d.Range(Cells(2, 3), Cells(lrow, 3)).PasteSpecial xlPasteValues

This does not:

s.Range(Cells(2, 8), Cells(lrow, 8)).Copy
d.Range(Cells(2, 3), Cells(lrow, 3)).PasteSpecial xlPasteValues

Why does VBA need the sheets to be activated if I've already specified them with the variables "s" and "d"? Thanks


回答1:


That's because when Range(...) and Cells(...) methods are not qualified, they operate on the Active Worksheet.

s.Activate

s.Range(Cells(2, 8), Cells(lrow, 8)).Copy

If s was not the active sheet, you would be requesting from s a range of cells that do not belong to it, but to the other, active worksheet. Because

       Cells(2, 8)     <==>   ActiveSheet.Cells(2, 8) 
       Cells(lrow, 8)  <==>   ActiveSheet.Cells(lrow, 8) 

To avoid this trouble, always qualify your ranges and cells:

 s.Range(s.Cells(2, 8), s.Cells(lrow, 8)).Copy

This is the correct approach; whenever you find yourself using stuff like Activate and Select, understand that you are most-likely doing something wrong. In good practice you will almost never need to use this stuff.



来源:https://stackoverflow.com/questions/41384018/vba-copy-and-paste-only-work-if-i-activate-the-sheet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!