The comment is a simple, expressive text which is used within the program. VBA comments are used to define what we are doing and why we are doing it.
Commonly the comments are used when you develop any workarounds or have complicated code.
VBA Comment Single Line
There are several ways to comment on the lines of code, such as single quotation (‘), comment block button in the toolbar, and adding the Rem keyword.
Putting a single quotation at the beginning of the line is the easiest way to comment a line in the program, such as:
NOTE: In the VBA, the green text is always used to display the Comments.
In the above example, we used a single quotation at the starting of the line to comment on the first line. After setting the quotation at the starting of the line, then the whole line is commented. And this line will not execute during the execution of the program.
If we put a single quotation somewhere in the line, then you can comment part of the code.
We can also use a second way of commenting on a line in the program by using the standard VBA button.
To display the standard VBA button, we need to add View → Toolbar → Edit on the VBA worksheet.
Now we can see two buttons in the toolbar that is Comment block and Uncomment block.
NOTE: we cannot add a quotation at the end of a line in the code while using this method.
Using Rem Keyword
To comment on any line, you can start that line with the Rem keyword. There is no need to use a single quotation or apostrophe.
Following are the limitation using the Rem keyword, such as:
- There should be at least one space between the start of your comment and the Rem keyword.
- We cannot use the Rem keyword in between a line to comment on the whole line.
- We must use the Rem keyword always as the first word.
VBA Comment Entire Block
We also need to comment on multiple lines or a block of code, and we have the same standard button comment block in the toolbar.
First, choose the lines that we want to comment and then click on the Comment button:
Now the whole block of code is commented. Similarly, by using the Uncomment button, we can uncomment a block of code.
Keyboard Shortcuts for Comment
To enable the shortcut keys for commenting follow the following steps, such as:
- Right, click on the toolbar.
- Select the Customize option and choose the Edit option.
- Then drag and drop the comment block next to the existing icons in the toolbar.
- Now the newly added button is visible in the toolbar.
- Click on the Modify and check Image and text option.
- Again click on the modify Selection and add the & at the beginning of the Comment Block, so the name of the button is “&Comment Block“.
Now, press Alt + C to comment on the selected line or block of lines in the program.
By repeating the whole process, we can Uncomment Block command, or we can use the shortcut key Alt + U.