VBA Code Guide
Jump to navigation
Jump to search
General
Following guidelines during coding makes code easier to read and to understand for you and others.
The following code guide is a summary of best practices in VBA projects.
Writing
- Line width
- Keep your line lengths under 80 characters.
- Printing code, that makes extensive use of unlimited line lengths looks very irritating when printed. Make use of line breaks
Indentation
- Indentation
- Use four spaces instead of tabs
- Using tabs in other editors than the VBE results in whitespace dependent on the application you are using the code in, which resulsts in inconsistent code layout.
- Four spaces indent enough to emphasize the indentation, two spaces are often to few, eight spaces too much.
- Keyword alignment
- In If and Case statements the "choice" keywords should be indented to the same level.
- Sometimes you see in Case statements that the Case lines are indented, but this is not consistent compared If/Else.
If blnResult Then
'Result code here
Else
'Else code here
EndIf
Select Case strResult
Case "My"
'My code here
Case "Their"
'Their code here
Case Else
'Default code here
End Select
Comments
- Section comment
- Use hashes / sharps (#) for section comments.
- Hashes / sharps are very "dark" and therefore ideal for making a significant separating comment.
- The comment is indented to the same level as the commented code
- Make the comment 80 characters wide in order to remind you of the desirable maximal length of your line; if indented a few levels the comment should be shorter, but you can ignore this for the time being and for practical reasons.
'################################################################################
'# Section
- Sub section comment
- Use equals (=) or dashes / hyphens (-) for sub section comments.
- For sub sections you need a less "dark" character. Some people prefer equal signs, other dashes / hyphens.
- The advantage of dashes / hyphens is, that you can use plus signs (+) in order to imitate a frame.
'+-------------------------------------------------------------------------------
'| Boxed comment
'+-------------------------------------------------------------------------------