How to Comment a Block of Code in VBA (With Example)

Commenting your code is an important habit to get into when writing Visual Basic for Applications (VBA) code. It helps to document your code and makes it easier to debug. To comment a block of code in VBA, you can use the ‘Option Explicit’ statement to add comments to multiple lines of code at once. To use this statement, begin your comment with an apostrophe (‘), then type the comment. The comment will be applied to all subsequent lines of code until another apostrophe is encountered. For example, you can comment a block of code with: ‘This code block calculates the answer to a specific problem. This will apply the comment to the following lines of code until another apostrophe is used.


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:

VBA comment block shortcut keys

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:

VBA comment block

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.

x