All About Indenting
Today's article is a quick practical tip about the code-writing process.
Proper indenting is one of the most important parts of creating readable code. Each logical "block" of code should be indented to distinguish it from the code that comes before and after it. Code blocks are often nested, leading to multiple levels of indentation.
Here's a quick example:
'Contrived routine that lists all the code modules
' in the current project and whether or not
' they are open in the VBA IDE
Sub ListModules()
With CurrentProject
Dim AccObj As AccessObject
For Each AccObj In .AllModules
If AccObj.IsLoaded Then
Debug.Print AccObj.Name; " is loaded"
Else
Debug.Print AccObj.Name; " is not loaded"
End If
Next AccObj
End With
End Sub
The above code has four blocks. From the outside in, they are:
Sub
...End Sub
With
...End With
For Each
...Next
If
...Else
...End If
When I write code with these sorts of blocks, I use the following approach:
- Write the opening line
- Press [Enter] twice
- Write the closing line
- Press [Up] then [Tab]
- Write the inner code
Practical Example
Here's how the above code would evolve in my development environment. (I use the pipe character [|
] in the code samples below to represent the position of the cursor.)
Detailed Breakdown of the First Block
Block-by-Block Overview
Why Do I Do It This Way?
This approach helps reduce compile errors, but that in itself is not a big deal. Compile errors are cheap and easy to fix.
Where this approach helps the most is in avoiding off-by-one type logic errors, such as ensuring a variable is being incremented on the correct side of a loop. This is important, as logic errors are the most difficult and expensive bugs to fix.
(That said, the best way to write code that's easy to read and to avoid block-related logic errors is to minimize the number of indented levels in your code in the first place. For example, if you have a procedure with six levels of indentation, you can probably split the three inner code blocks out into a standalone procedure and cut your levels of indentation in half.)
Reader Feedback
I assume that most developers use this approach, but I could be wrong.
Newer development environments (i.e., not VBA) often have a code-block-autocomplete feature built-in or available via third-party plugins. Thus, this might be a problem somewhat unique to VBA in the year of our Lord 2023.
Do you use a similar approach when writing code in VBA? If not, what approach do you use? Or do you not really think about it? Maybe I'm just a weirdo for obsessing over this level of programming minutiae. Let me know in the comments below.