What is good practice and good code hygiene? Putting code in Modules or Sheets?
I have this Excel Workbook, with user interfaces in each sheet. Each sheet within the workbook does a different part of some overall task. Should I place the code relevant to each sheet inside the Sheet objects, or in Modules? Group into one module, or separate modules?
I'm using Excel 2003.
Insert VBA code to Excel WorkbookRight-click on your workbook name in the "Project-VBAProject" pane (at the top left corner of the editor window) and select Insert -> Module from the context menu. Copy the VBA code (from a web-page etc.) and paste it to the right pane of the VBA editor ("Module1" window).
Code vs Sheet vs ThisWorkbook Module Each of these modules allow us to store macros that we can run by pressing a button or from the Macro window. However, the Sheet and ThisWorkbook objects allow us to store event procedures (macros) that will run when a user takes an action in the workbook.
You can't run a macro in a workbook that is closed. You can't run a macro that affects a workbook that is closed. You can put code in Inventory.
Another option is to use VBA code like the following to protect the worksheet and it allows macros to make changes but the user cannot make changes directly on the worksheet. It is simply an example of protecting.
Definitely in Modules.
Since the tooling is so poor in primitive systems such as Excel VBA, best practices, obsessive code hygiene and religious following of conventions are important, especially if you're trying to do anything remotely complex with it.
This article explains the intended usages of different types of code containers. It doesn't qualify why these distinctions should be made, but I believe most developers trying to develop serious applications on the Excel platform follow them.
There's also a list of VBA coding conventions I've found helpful, although they're not directly related to Excel VBA. Please ignore the crazy naming conventions they have on that site, it's all crazy hungarian.
In my experience it's best to put as much code as you can into well-named modules, and only put as much code as you need to into the actual worksheet objects.
Example: Any code that uses worksheet events like Worksheet_SelectionChange or Worksheet_Calculate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With