8

Could anyone tell me why, when I refer to a particular sheet, I could use:

workbooks("A").worksheets("B").activate

but not

workbooks("A").worksheets("B").select 

?

1 Answer 1

22

You can't select a sheet in a non-active workbook.

You must first activate the workbook, then you can select the sheet.

workbooks("A").activate
workbooks("A").worksheets("B").select 

When you use Activate it automatically activates the workbook.

Note you can select >1 sheet in a workbook:

activeworkbook.sheets(array("sheet1","sheet3")).select

but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.

8
  • Thank you a lot! I remember I read from somewhere that .select is not recommended to use, do you happen to know why? Commented Jul 11, 2013 at 23:41
  • 1
    That advice typically comes from using macro-recorder-generated without any edits. Typically the recorder generates code like Range("A1").Select then Selection.Copy whereas it's much cleaner just to do Range("A1").Copy. If your code uses Select (particularly on ranges) then it can break if the "wrong" sheet is active, making your macro much less robust. Avoiding select and working directly on the object itself is faster and less brittle. Commented Jul 11, 2013 at 23:52
  • 1
    I see! Thanks a lot! Can I ask one more question? Under what circumstances, the activesheet will be changed, say if the current activesheet is B and then I change the format or value of a cell in sheetA, will the activesheet become sheetA? Commented Jul 12, 2013 at 17:31
  • 1
    The activesheet only changes if you set it in code or change it manually. However, it's easy when you have a lot of code to forget which sub does or doesn't switch sheets, so it's best to avoid relying on some specific sheet being active at any given time and instead always refer to it directly (by name or by codeName). Commented Jul 12, 2013 at 17:46
  • Got it. Really appreciate it! Commented Jul 12, 2013 at 17:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.