ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   Can't select worksheet (https://www.excelbanter.com/excel-programming/384754-cant-select-worksheet.html)

bw

Can't select worksheet
 
The following code is called from Sheet2:

1. Worksheets("Sheet1").Unprotect
2. Worksheets("Sheet1").Activate
3. Cells(3, 1).Copy 'THIS CELL IS COPIED FROM SHEET2....and is WRONG
4. Worksheets("Sheet1").Cells(I, 1).Copy 'THIS CELL IS COPIED FROM
SHEET1....and is CORRECT

Why doesn't line 3 do the copy from Sheet1 as I had intended?

Thanks,
Bernie


Jim Thomlinson

Can't select worksheet
 
When you do not explicitly specify sheets you leave things to chance and
prone to errors as code is modified... Try this

with Worksheets("Sheet1")
.Unprotect
.Activate
.Cells(3, 1).Copy
.Cells(I, 1).Copy
end with

Code in standard code modules refer to the active sheet unless otherwise
specified. Code in sheets refer to the sheet they are in unless otherwise
specified. That being said ALWAYS explictly reference the sheets you are
working with. It makes your code more readable and much less prone to run
time error.
--
HTH...

Jim Thomlinson


"bw" wrote:

The following code is called from Sheet2:

1. Worksheets("Sheet1").Unprotect
2. Worksheets("Sheet1").Activate
3. Cells(3, 1).Copy 'THIS CELL IS COPIED FROM SHEET2....and is WRONG
4. Worksheets("Sheet1").Cells(I, 1).Copy 'THIS CELL IS COPIED FROM
SHEET1....and is CORRECT

Why doesn't line 3 do the copy from Sheet1 as I had intended?

Thanks,
Bernie



Vergel Adriano

Can't select worksheet
 
Because the code is in Sheet2, Cells(3,1) would refer to A3 in Sheet2, even
if Sheet1 was the activesheet. If it were in a code module, Cells(3,1) would
have referred to A3 in the activesheet. To be safe, always qualify your
ranges.

"bw" wrote:

The following code is called from Sheet2:

1. Worksheets("Sheet1").Unprotect
2. Worksheets("Sheet1").Activate
3. Cells(3, 1).Copy 'THIS CELL IS COPIED FROM SHEET2....and is WRONG
4. Worksheets("Sheet1").Cells(I, 1).Copy 'THIS CELL IS COPIED FROM
SHEET1....and is CORRECT

Why doesn't line 3 do the copy from Sheet1 as I had intended?

Thanks,
Bernie




All times are GMT +1. The time now is 03:34 PM.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
ExcelBanter.com