Home > Articles

  • Print
  • + Share This
  • 💬 Discuss

Like this article? We recommend

Nesting Code

Nesting code is another use of good form, and Excel provides excellent support for indentation of code to easily spot where code is nested. Nested code includes the indented lines of code between conditional if statements and loops (for, do, and so on.). The code between these nests can become messy quickly when there are multiple levels of nested code as follows:

Do
Do While Counter < 20
Counter = Counter + 1
If Counter = 10 Then
Check = False
Exit Do
End If
Loop
Loop Until Check = False

Simply use the Tab key to indent, and all subsequent lines will have the same indent—do not use the space key. In addition, the Shift-Tab combination will reverse the tabs of your code. You can even select multiple lines and use the Tab key to indent entire blocks accordingly. If we use good form as in the previous example, the following code becomes easier to read.

' Let's loop until something happens
Do                 

  ' Well let's just loop 20 times
  Do While loopCount < 20    
    loopCount = loopCount + 1 

    ' I'm bored, let's only loop for 10
    If loopCount = 10 Then

      ' That's enough
      letsBail = TRUE    
      Exit Do  
       
    End If

  Loop

Loop Until letsBail = TRUE     
' Wasn't that fun?

Using spaces is another good style for nested code that helps make the program more readable. Adding spaces and comments does not adversely affect the performance of the worksheet, so use spaces and comments often and without fear.

  • + Share This
  • 🔖 Save To Your Account
Managing Data with Excel

Like this article? We recommend

Managing Data with Excel

Discussions

comments powered by Disqus