Commenting Blocks and Loops

Published on August 18, 2009

Using nested block and loop structures is often a necessary part of any VBA macro. Multiple nested structures can be very long and difficult to follow when trying to read and debug the code. To aid in the legibility of your code always indent the code within the block or loop structure. For longer running structures copy the initial test expression and paste it as a comment after the closing statement. See the example macro below.

‘Example showing use of indents and comments
Public Sub MyMacro()
    Dim FileIsOpen As Boolean    
    Dim iCount As Integer    

    'Do stuff here

    'Indent lines of code under every block and loop
    'Add comment after block/loop closing statement
    If FileIsOpen Then

        For iCount = 0 To 10
            Select Case iCount
                Case 0
                    'Indent 0 condition code here
                Case 10
                    'Indent 10 condition code here
                Case Else 
                    'Indent Else condition code here
            End Select    'iCount

        Next    'iCount = 0 To 10
        MsgBox "File is closed", vbInformation, "MyMacro"

    End If   'FileIsOpen

    'Do more stuff here
End Sub

Like this article? Share it!

Leave a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Privacy Policy