Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do I need to refer ThisWorkbook (Excel VBA)

Tags:

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 (i.e. ThisWorkbook)?

like image 220
martin.lindenlauf Avatar asked Dec 02 '25 13:12

martin.lindenlauf


1 Answers

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.

like image 59
d-stroyer Avatar answered Dec 04 '25 04:12

d-stroyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!