简体   繁体   中英

do I need to refer ThisWorkbook (Excel VBA)

I do some VBA operations on specific sheets in a Workbook that may be copied later, enabling the end user to open more than one copy at a time (and filling the tables with different data).

Question:
Do I need to refer explicitly ThisWorkbook.Sheets(strMySheetName) to avoid any code to operate on the sheet with the same name but inside another copy of the workbook (opened at the same time), or does the Sheets collection always refer to the workbook the code resides in (ie ThisWorkbook )?

Short answer : No you don't need to.

The default context of execution of the macro it the currently active Workbook. So if your macro is launched through action on the Workbook sheets (calculate, widgets such as buttons, save or load events), there is no risk.

If your macro is cross-workbook, can be triggered by action on another workbook or intends to set focus, load, modify other workbooks, then its a must to specify ThisWorkbook.

As already mentionned in the comments of your questions, alternatives such as Workbook("myworkbookname") are better for disambiguation in many cases, but have side effect in case you change the filename.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM