This script works fine when I’m viewing the "Temp" sheet. But when I’m in another sheet then the copy command fails. It gives an Application-defined or object-defined error:
Sheets("Temp").Range(Cells(1), Cells(1).End(xlDown)).Copy
Sheets("Overview").Range("C40").PasteSpecial
I can use this script instead, but then I have problems with pasting it:
Sheets("Temp").Columns(1).Copy
Sheets("Overview").Range("C40").PasteSpecial
I don’t want to activate the "Temp" sheet to get this.
What else can I do?
Your issue is that the because the
Cellreferences inside theRange‘s are unqualified, they refer to a default sheet, which may not be the sheet you intend.For standard modules, the
ThisWorkbookmodule, custom classes and user form modules, the defeault is theActiveSheet. ForWorksheetcode behind modules, it’s that worksheet.For modules other than worksheet code behind modules, your code is actually saying
For worksheet code behind modules, your code is actually saying
In either case, the solution is the same: fully qualify the range references with the required workbook:
Note: When using
.End(xlDown)there is a danger that this will result in a range extending further than you expect. It’s better to use.End(xlUp)if your sheet layout allows. If not, check the referenced cell and the cell below forEmptyfirst.