Excel VBA Best Practice
Fuller coverage of Excel VBA Best Practice is in our Best Practice series, Starting here
Codematic VBA Code Convention for Excel VBA
(Note this advice is specific to Excel VBA in business applications. Other languages and other applications have very different requirements).
Pretty simple really, easy to remember and easy to implement:
- Always use Option Explicit, usually use Option Private Module.
- Give Module level variables a scope qualifier prefix g_, p_ or m_ (Global (all open workbooks), Public (this workbook), or Module). Scope everything as tightly as possible. Use procedure level scope where possible and pass values by parameters.
- Use meaningful names for all procedures and variables. Do not bother with convoluted data type prefixes, that is inappropriate for business level applications, makes the code harder to read and adds very little of value. The compiler will pick up any obvious data type errors. Used mixed case descriptive names - if the name is too long then probably the procedure is too.
- Procedures should fit on one screen - ie be 40-50 lines long maximum.
- Avoid most comments - make the executable code meaningful and simple instead.
- Avoid magic numbers and strings - use constants.
- Never comment what the code does - that should be crystal clear from the code, comment WHY something is done, especially if it is unusual. Add a couple of sentences to provide an overview of a module or class.
- Pass parameters ByVal (ByRef is the default) - only use ByRef where you intend to modify the parameter and pass the change back to the caller.
- Avoid Application.Run where possible as it breaks the error handling stack.
- Use additional tools. See links page for some suggestions.
- Be aware of other options if VBA appears inappropriate for certain aspects of the project.
- Vary any rules you the developer feel do not promote clarity, simplicity and safety.
- If you really want to write high quality code read Code Complete 2 by Steve McConnell - and then apply it.
- Fuller info is in Simons VBA Best Practice slides(ppt) , or as web pages starting here.
Please contact us with any questions.
25 January 2012 - UK Excel Developer Conference - London
Products for sale:
New information about the missing FileSearch feature in Office 2007 and details of our pragmatic solution (Current price GBP 30.00)
Instant Excel worksheet protection remover and password recovery (Current price GBP 15.00)
Classic Ribbon Tab
Add Excel 97/2000/2002/2003 compatible menu structure to Excel 2007
(Current Price GBP 10.00)
Products coming soon:
(Find and control external links in Excel Workbooks)
Due by Q1 2111.
(Excel VBA based spreadsheet auditing tool)
Due before the end of 2111.