Can't select worksheet

  • Thread starter Thread starter bw
  • Start date Start date
B

bw

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
 
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.
 
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top