3

When you just type worksheets() what is the default scope ActiveWorkbook or ThisWorkbook? For those who do not know these distinctions they are extremely important especially in Excel 2013 when you want macros to run when you switch to different workbooks.

7
  • It is Activeworkbook unless otherwise specify in preceding codes
    – Alex
    Feb 10, 2015 at 18:51
  • @Alex is there a way to change the default behavior with preceding code so that it always references ThisWorkbook? Or would I have to simply declare ThisWorkbook for each time I grab something (this is how I do it currently) .
    – CodeCamper
    Feb 13, 2015 at 16:55
  • As Tim's answer below, you could put your code in thisworkbook module and unqualified worksheets will be default to thisworkbook
    – Alex
    Feb 17, 2015 at 15:17
  • @Alex what is an unqualified worksheet vs a qualified worksheet?
    – CodeCamper
    Feb 18, 2015 at 20:20
  • sorry it was poorly explained. I meant to say an unqualified worksheet() object.
    – Alex
    Feb 18, 2015 at 20:31

1 Answer 1

18

In a standard module an unqualified Worksheets() will always reference the ActiveWorkbook. In the ThisWorkbook module, the implicit qualifier is Me and that will reference the containing workbook.

Likewise, an unqualified Range() or Cells() (or Rows()/Columns()) in a standard module will reference the ActiveSheet, but in a sheet code module the implicit qualifier is Me, and will reference the corresponding worksheet.

Unqualified...    |   Where            | Implicit Qualifier
-----------------------------------------------------------------------
Worksheets(),     |  ThisWorkbook      | Containing workbook (Me)
Sheets()          |  --------------------------------------------------
                  |  Any other module  | Active workbook (via [_Global])
-----------------------------------------------------------------------                     
Range(), Cells(), |  Sheet module      | Containing sheet (Me)
Rows(), Columns(),|  --------------------------------------------------
Names()           |  Any other module  | Active sheet (via [_Global])
-----------------------------------------------------------------------

The easy way to avoid having to remember any of this is to always fully qualify any Worksheets, Sheets, Range, Cells, or Names reference.

Qualify the member call with Me when referring to ThisWorkbook in that module's code-behind, or when referring to Sheet1 in that module's code-behind.

0

Your Answer

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

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