Commenting out code in VBA
Part one of a three-part series of blogs

Commenting code is an art form! This series of blogs explains why, how and when to comment in VBA.

  1. Why Write Comments in Excel Visual Basic (this blog)
  2. Adding Comments in VBA macros for Excel
  3. Commenting Out Code in Excel Visual Basic

This blog is part of our Excel macros online tutorial series.  Alternatively, come on one of our VBA classroom training courses.

Posted by Andy Brown on 28 April 2011

You need a minimum screen resolution of about 700 pixels width to see our blogs. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

Why Write Comments?

All good programmers use comments liberally.  To see why, consider the following excerpt of code, taken from Excel VBA:

Range("A1").Select

ActiveCell.End(xlDown).Select

ActiveCell.Offset(1, 0).Select

ActiveCell.Value = InputBox("Choose a Wise Owl")

Now compare this with exactly the same code, but commented:

'go to the bottom of column A

Range("A1").Select

ActiveCell.End(xlDown).Select

 

'go one cell further, to first blank cell …

ActiveCell.Offset(1, 0).Select

 

'… and set the value of this cell to be the Wise Owl name typed in

ActiveCell.Value = InputBox("Choose a Wise Owl")

We think the second code excerpt is far easier to read and understand!

Here are 2 good reasons to use comments in your code:

Reason Notes
Intelligibility You may understand your code now, but will you know what it was meant to do when you revisit it in 6 months' time?  Will your colleague understand it when you leave your company?  Comments make code easier to read and follow.
Clearer thought process It sounds strange to say it, but commenting code as you write will help you think about what you're trying to do.  If you write the line:

'go to the bottom cell in the first column

you've already thought about what you're trying to achieve, and are more likely to translate this into code correctly.

As a rough guide, you should add a comment for every 2-3 lines of code on average.

That's why you should comment your VBA code - now read on for how to do it!

  1. Why Write Comments in Excel Visual Basic (this blog)
  2. Adding Comments in VBA macros for Excel
  3. Commenting Out Code in Excel Visual Basic
This blog has 0 threads Add post