简体   繁体   中英

VBA Excel: Copying across sheets using alphanumeric range vs cells

Bit of a bizarre title, I'll explain what I'm asking.

The use of .Range("A1:B2").copy vs using .Range(Cells(1, 1), Cells(2, 2)).copy .

Both will work, but only when I'm on the actual sheet. If I'm on a different sheet when the macro gets called, then only the alphanumeric range will work.

Actual code in question:

CurrentExtractSheet.Range("A2: AR" & (CurrentExtractCount + 1)).Copy
PreviousExtractSheet.Range("A2").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

vs

CurrentExtractSheet.Range(Cells(2, 1), Cells(CurrentExtractCount + 1, 45)).Copy
PreviousExtractSheet.Range("A2").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

So what I'm asking is there any way to work around this issue (I prefer using the Cells method rather than alphanumeric ranges)? Does Cells require an activesheet first (also which I don't particularly like)?

Thanks in advance.

You do not need to set CurrentExtractSheet to be the ActiveSheet, but you do need to include it with your Cells command as so...

CurrentExtractSheet.Range(CurrentExtractSheet.Cells(2, 1), CurrentExtractSheet.Cells(CurrentExtractCount + 1, 45)).Copy

or

With CurrentExtractSheet
 .Range(.Cells(2, 1),.Cells(CurrentExtractCount + 1, 45)).Copy
End With

When doing Cells(x,y) without specifying a sheet, your are in fact referening to the activesheet.

So, CurrentExtractSheet.Range(Cells(2, 1), Cells(CurrentExtractCount + 1, 45)) is equivalent to CurrentExtractSheet.Range(Activesheet.Cells(2, 1), Activesheet.Cells(CurrentExtractCount + 1, 45))

When CurrentExtractSheet is not the active sheet it fails.

There are several ways to avoid this error

With CurrentExtractSheet
    Range(.Cells(2, 1), .Cells(CurrentExtractCount + 1, 45)) ...
End With

Note, when you specify the sheets for the two .Cells references you don't need to qualift Range

Another otpion

CurrentExtractSheet.Cells(2, 1).Resize(CurrentExtractCount, 45) ...

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