You can use a single quotation ( ‘ ) in VBA to comment out a single line of code.
However, there is no built-in option in VBA to comment out a block of code.
Fortunately, there is a neat way to create a shortcut key that you can use to comment out a block of code and the following step-by-step example shows how.
Step 1: Customize the Toolbar
Within the VB Editor, right click anywhere on the toolbar and then click Customize:
Step 2: Add Comment Block to Toolbar
Click the Commands tab, then under Categories click Edit, then under Commands click Comment Block.
Then drag the Comment Block option onto the Toolbar. An icon should now appear for the comment block on the toolbar:
Step 3: Create Comment Block Shortcut Key
Next, click the Comment block icon on the toolbar (a black box will appear around the icon).
In the Customize panel, click the Modify Selection dropdown, then in the Name field type an ampersand ( & ) symbol in front of Comment Block and press Enter:
Then click the Modify Selection dropdown again and click Image and Text from the options:
Then click Close on the Customize window.
You will now be able to highlight a block of code and press Alt + C to comment out the entire block.
Step 4: Use the Comment Block Shortcut Key
Suppose we would like to comment out the entire block of code in the following sub procedure:
Once we’ve highlighted this block of code, we can simply press Alt + C and the entire block will be commented out:
Note that you can also create a shortcut key to uncomment a block of code by repeating the same steps above for the Uncomment Block option.
Once you’ve done so, you will then be able to highlight a block of code and press Alt + U to uncomment out the entire block.
The following tutorials explain how to perform other common tasks in VBA: