VBA Best Practice There is a lot of information floating around about how to get various things done in VBA, how to make the best use, or sometimes just the most use of VBA and Excel. This section aims to add an element of Quality and Best Practices. These are just general guidelines, a professional developer will always assess the options and make the appropriate choice in their specific situation. These suggestions are specific to Excel VBA in commercial settings, many will not translate to other technologies or other settings. VBA Best Practice Series High Quality Code - Variables- Don't reuse variables for different purposes, avoid 'temp'
- Use clear data types, and control them (watch out for implicit coercion)
- Variants are often easier to work with than arrays
- Pass parameters byVal if they are not to be changed (watch for coercion)
- Explicitly use byRef in an input parameter is to be changed, but watch for signs to redesign
- Don't implicitly use the default property, be explicit (eg range.value)
- Magic numbers and strings should be made into constants.
- Use explicit data casting Cstr() Cbool() etc
- Code with early binding if at all possible (new), change to late binding to support multiple versions or if component may not be installed. Late can be slower and may need better error handling.
- Can define all variables together at top or just before they are needed both have pros and cons.
- Sometimes a simple i, j, x or y is better than a long datatype prefixed descriptive name for a loop index
- Boolean variable should be named so True or False make sense - eg use done rather than status
- Booleans should be positive eg if not found then. rather than if not notFound then.
- Never mess with a loop counter within the loop.
|
|
Upcoming Events:
25 January 2012 - UK Excel Developer Conference - London
Products for sale:
AltFileSearch

New information about the missing FileSearch feature in Office 2007 and details of our pragmatic solution (Current price GBP 30.00)
wsUnprotector
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:
Link Manager
(Find and control external links in Excel Workbooks)
Due by Q1 2111.
XLAnalyst Pro
(Excel VBA based spreadsheet auditing tool)
Due before the end of 2111. |