VBA comment multiple lines

VBA - Visual Basic for Application

Anyone who programs a lot in the Microsoft Office area with VBA and uses the associated VBA editor also wants to comment out entire blocks of code quickly.

In some of our other posts we have described how to automatically process emails with macros when they arrive in the inbox. Or how to send e-mail attachments automatically to the printer. Such and other functions have to be tested a lot during development, and sometimes you want to comment whole methods and functions and then comment them back in.

Unfortunately, VBA does not offer the possibility to comment the code as in other programming languages:

/*code line X
code line Y
code line Z*/

Instead, in VBA you have to put the “apostrophe” in front of each line of code.

'code line X
'code line Y
'code line Z

If you want to comment whole methods and functions, it can be very annoying to set or remove the “apostrophe” manually before each line.

Comment code block in VBA

But fortunately, the VBA editor offers a corresponding function via a toolbar called “Edit”. However, this toolbar is not shown by default. To show it, go to View => Toolbars => Edit in the menu.

Screenshot VBA Editor Menu View Toolbars Edit
Show Toolbar Edit

If the Edit toolbar appears floating in the program, you can also pin it to the existing toolbar.

Screenshot Toolbar Edit with tools to comment and uncomment multiple lines (code block)
Edit toolbar with buttons for comment and uncomment multiple lines (code block)

There are now two icons here. One for commenting and one for uncommenting.

To do this, mark the relevant lines of code and click on the respective symbol, as shown in the following two images. The “apostrophe” is then automatically prepended or removed for all marked lines.

Screenshot VBA Editor comment multiple lines
Mark code lines and click button for “Comment Block”
Screenshot VBA-Editor Uncomment multiple lines of code
Mark lines of code and click button for “Uncomment Block”

So it is still possible to comment several lines in the VBA code in a halfway practicable way.

Leave a Reply

Your email address will not be published. Required fields are marked *