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&
This blog will contain useful tips and tricks to make using Excel easier. It's a great piece of software, but is so complex that it takes years to master. Luckily The Master of Excel is here to help!
Showing posts with label Coding Standard. Show all posts
Showing posts with label Coding Standard. Show all posts
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.
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.
Labels:
Coding Standard,
VBA
Excel VBA coding standard: Always use explicitly declared variable types
Standard
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.
- Always use "option explicit" at the top of your modules to force variable types to be declared.
- Never use the Variant type. It is slow, not memory efficient and can hide errors, which creates potentially nasty bugs.
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.
Labels:
Coding Standard,
VBA
Subscribe to:
Posts (Atom)