简体   繁体   中英

range.copy Destination “A1” vs “Cells(1,1)” Excel/VBA

Consider the below:

    Sheets("X").Activate
    Sheets("X").Range(Cells(1, 1), Cells(1, 30)).Copy Destination:=Sheets("Y").Range("A1") 'Syntax 1
    Sheets("X").Range(Cells(1, 1), Cells(1, 30)).Copy Destination:=Sheets("Y").Range(Cells(1, 1)) 'Syntax 2

Why does Syntax 1 works while Syntax 2 runs into 'Application-defined or object-defined error'?

You haven't qualified the sheet name. So the copy happens on the ActiveSheet it then tries to reference Cell(1,1) from the ActiveSheet but on sheet Y:

Sheets("Y").Range(Cells(1, 1))

Sheets("Y") is sheet Y. Cells(1,1) is the ActiveSheet.

The copy only works because you activate sheet X first. Remove that line, select another sheet and it will fail on that as well.

Unqualified Cells(1,1) belongs to the ActiveSheet, which is currently Sheets("X"), so it does not belong to Sheets("Y") .

OTOH: this should work:

Destination:=Sheets("Y").Range(Sheets("Y").Cells(1, 1), Sheets("Y").Cells(1, 1)) 
'                             ^^^^^^^^^^^^^

Dont use unqualified ranges. Drop the Activate stuf altogether from your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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