Showing posts with label Coding Standard. Show all posts
Showing posts with label Coding Standard. Show all posts

Excel VBA coding standard: do not use Type-Declaration Characters

There are a number of Type-Declaration Characters that exist in VBA as a hangover from BASIC.  These are: % (Integer), & (Long), ! (Single), # (Double), @ (Currency) and $ (String).  They should not be used to declare variables.

Rationale

Consider the following variable declarations.  Which is easier to read and understand?

Dim x As Long

Dim x&

Excel VBA coding standard: declare each variable on its own line

Standard

Each variable should be declared on its own line to aid clarity and reduce the chance of unintentional behaviour.  For example:
Dim x As Long
Dim y As Long
Dim ratio As Double

Rationale

VBA has a peculiar way of declaring types when multiple variables are declared on the same line.  The following two pieces of code are not equivalent:
Dim x, y, z As Long

Dim x As Long, y As Long, z As Long

In the first example, x and y become Variant type and z is a Long (which is probably not what the author intended).  In the second example they are all Longs.  This is not consistent with many other programming languages and is likely to cause confusion for other programmers, or even the original author.

Excel VBA coding standard: Always use explicitly declared variable types

Standard
  1. Always use "option explicit" at the top of your modules to force variable types to be declared.
  2. Never use the Variant type.  It is slow, not memory efficient and can hide errors, which creates potentially nasty bugs.
Rationale

VBA for Excel supports the Variant variable type and by default will not insist that variable types are declared.  Whilst this makes basic coding easier, it can easily lead to very nasty bugs and slow/inefficient code, as we will now explore.