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