Basic practices for easy readable VBA code
1 Use option explicit
This will force you to declare variables.
Option explicit can be typed in at
the top of your module before any code or it can be automatically placed there
by selecting the following items from the menu:
àTools
Options and then select “require variable declaration”
2 Declare the variables as you use them
If you declare the variables at the top of
the code it becomes very messy
3 Indent your code and use blank lines
Shift + Tab align all the code up
Tab can then be used to indent the code
line by line where appropriate between
loops and other programming statements.
4 Give variables nice names
Use long descriptive names. You don’t
have to use e.g. ‘lng’ in front if it is a long variable. Control + Space will
help to complete the variable name when typing it (in case you worry that the
writing the names will slow down programming) and then name of the variable
will give an indication of the variable type.
Always use i and j when it comes to
loops.
5 Use magic numbers
These are numbers that appear in
our code that are not 0 or 1.
They have some magic number that we
don’t really know what it will represent.
These numbers should be represented
by a constant / Enum. Look at the code below which is difficult to read:
result
= rg.Cells(row + 6, ( 1 * 3) + 4).value
Bonus
– result * 4
When we use PasteSpecial we have different
options like PasteAll, PasteComments ect. All these are basically a text
representation of a number.
I we look at Enums (short for Enumerator)
as in the code below:
Enum DataColumns
dcAmount
= 1
dcCheck
= 2
dcResult
= 3
dcBonus
= 4
End Enum
Each column is represented by an Enum and
we can use the Enum name instead of a number in our code. This make changes
easy when there are changes in columns.
We can further do the following to the Enum
to use it even more to our benefit:
Enum DataColumns
dcAmount
= 1
dcCheck
= dcAmount + 1
dcResult
= dcCheck + 1
dcBonus
= dcResult + 1
End Enum
6 Use variables instead of ranges
This is unique to Excel VBA but the
most important technique
The code below flow from the
previous example and look how easy it is to read:
Sub ReadDataNew()
Dim
rg as Range
Dim
rg = shData.Range(“A1”).CurrentRegion
Dim
amount as Long, check as Long, result as Long, bonus as Long
Dim
i as long
For
i = 1 to rg.Rows.Count
amount
= rg.Cells(i,dcAmount).value
check
= rg.Cells(i,dcCheck).value
result
= rg.Cells(i,dcResult).value
bonus
= rg.Cells(i,dcBonus).value
If
amount = check Then
result
= result + bonus
ElseIf
amount < check Then
Result
= result – bonus
EndIf
Next
i
7 Do not repeat code
This can be easily achieved by
using function and sub procedures.The advantage is that if there are changes to
code it only needs to be changed at one place and not all over you program.
Comments
Post a Comment