Visual basic excel комментарии

Once you start writing VBA codes, there’s an important thing that you need to learn along with that and that’s using COMMENTS in your VBA codes.

The point is: Using VBA COMMENT is quite easy and simple, the only thing you need to learn is to do it effectively.

So today, I’ll be sharing with you all the details about using comments in VBA and all the options related to them.

A VBA COMMENT is a green line of text that helps you to describe the written code. In simple words, a comment is a line of text which is not a code and VBA ignores it while executing the code. It’s a good practice (I’d say one of the best) to add comments in your VBA codes.

(Video) Understanding VBA Comments

steps-to-add-a-vba-comment

As I said commenting in a VBA code is one of the best practices and there are a few benefits that come with it.

  • Helps you to Document your Work: You can use a comment to describe how code works, which can help you in the future to recall it easily or any other user.
  • Track the Changes: If some codes need you to change them frequently you can use comments to track or record changes within the code.
  • Describe a Function Procedure: When you write a procedure you can add a comment at the starting to describe the purpose of this procedure and how it works.
  • Describe a Variable: Variables are one of the most important things that you need to use while writing a VBA code and you can use a comment to describe a variable.
  • Debug Your Code: You can use VBA comments to debug the code by converting code lines into comments for testing.

Steps you need to follow to add a comment in a VBA code:

  1. First, click on the line where you want to insert the comment.
  2. After that, type an APOSTROPHE using your keyboard key.
  3. Next, type the comment that you want to add to the code.
  4. In the end, hit enter to move to the new line and the comment will turn green.
steps-to-add-a-vba-comment

The moment you do this the entire line of the code will turn green which means that line is comment now.

If you look at the below code where I have used a comment to add a description of the procedure.

You simply need to add an apostrophe before turning it into a comment and VBA will ignore it while executing the code.

The second method is to use the comment block button from the toolbar. This button simply adds an apostrophe at the start of the line.

To use this button, first of all, you need to select the line of the code and then click on the button.

steps-to-add-a-vba-comment

Next to the Comment button, there’s one more button “Uncomment” which you can use to uncomment a line (This button simply removes the apostrophe from the line of the code).

There could be a situation where you need to enter a comment in multiple lines, like a block of the comments.

But here is one thing which you need to note down, every line of comment needs to start with an apostrophe, so if you want to add multiple lines of comments every line should have an APOSTROPHE. 

The easiest way is to select all the lines and then use the comment button from the toolbar or you can also add an APOSTROPHE at the starting of each line.

enter-a-multi-line-vba-comment

The moment you click the comment button it will convert all the lines into a multi-line comment block.

multi-line-vba-comment-block

Update: There’s one thing that I have discovered recently if you have a block of comment line (continuous), you can use a line continuation character (an underscore must be immediately preceded by a space).

vba-comment-with-line-break

In the above example, I have used an apostrophe only at the start of the first line of the comment, the rest two-line don’t have an apostrophe but I have used line continuation character to give a line break at the end of the first line and the second line.

This is the third way to insert a comment into a VBA code. Well, this is not a popular way but still, you can use it. So instead of using an apostrophe, you can use the keyword REM at the starting of a comment line.

REM stands for remarks.

vba-comment-with-rem

Now, in the above example, I have used “REM” at the start of the line of the code and then the line of the code. But, there’s no button to add REM, you have to type it.

When you record a macro code using the macro recorder, you get an option to add a description before you record it.

So when you open the record macro dialog box, there is a “Description” input box where you can add your comment and then start recording.

vba-comment-macro-recorder

And when you open the VBE to see the recorded code, you can see the code which you have added as a comment.

When you add a comment while recording a macro, VBA adds a few apostrophes as blank comments.

vba-comment-in-recorded-macro

This is a quite smart way to use a comment in the same line where you have written code. In the below example you can see that I have three lines of code, where I have added comments after each line to describe it.

vba-comment-in-the-same-line

So once you complete a line of code you can use enter a comment after that in the same line.

Truly speaking there’s no (by default keyboard shortcut) to use to insert a comment. But thanks to Gaurav, I have found a way to create a shortcut key to insert an apostrophe.

Follow the below steps:

Now you can convert a line into a comment by using the shortcut key Alt + C.  And if you want to create a shortcut key for the uncomment button you can simply use the above steps to add the uncomment button to the toolbar and the shortcut key for it will be Alt + U.

VBA gives you an option to change the format of the comment if you want to do so. From the Tools ➜ Options ➜ Editor Format, click on the comment text.

change-format-of-the-vba-comment

As you can see, I have changed the color of the comment text from green to blue. Now all the comments which I have in the code window are in blue color.

vba-comment-with-blue-font-color

Return to VBA Code Examples

This article will teach you how to comment a single line or multiple blocks of code in the VBA Editor. Instead, if you want to learn about how to interact with Excel Cell Comments using VBA read that article.

In Excel VBA, there are several ways to comment lines of a code:

  • Single quotation (‘)
  • Comment block button in the toolbar
  • Adding the Rem keyword.

The easiest way to comment a line of a code is putting a single quotation at the beginning of the line:

   'Sheet1.Range("A1").Value = "Test"

Notice that in VBA, comments are always displayed as green text.

As you can see in the example, we put a single quotation at the beginning of the first line in the procedure and commented it. If a quotation is put at the beginning of the line, the whole line is commented and will be skipped during execution of the code.

You can also comment part of the code if you put a single quotation somewhere in the line.

In that case code after a quotation will be skipped:

   Sheet1.Range("A1").Value = "Test"  'The example of partial line commenting

Now we commented only part of the line. This is a good way for writing inline comments in a code.

The second way for commenting a line in a code is using the standard VBA button for comment in the toolbar. In order to display this button, you need to add it: View -> Toolbars -> Edit. Now you can see two buttons in the toolbar: Comment block and Uncomment block.

vba comment block

Simply highlight your desired line(s) of code and click one of the buttons. This will comment/uncomment entire lines.  Please note that this method will not allow you to add a comment to the end of a line of code.

You can also use the keyword Rem. In order to comment a line, you need to put this keyword at the beginning of a line:

Rem   Sheet1.Range("A1").Value = "Test"

Similarly to comment button, the Rem keyword allows you to comment just a whole line of a code, which means that you can put it only at the beginning of a line:

Apart from commenting a single line, we often need to comment multiple lines, a block of code. In order to do this, we can the same standard button Comment Block in the toolbar which we used for commenting a single line. First, we need to select all the lines that we want to comment and then click on the button:

Private Sub CommentEntireBlock()

'    Sheet1.Range("A1").Value = "Test"

'    If Sheet1.Range("A1") = "Test" Then
'        MsgBox "The value of A1 cell is: Test"
'    End If

End Sub

As a result, the whole block of code is commented.

Similarly, we can uncomment a block, by clicking on the Uncomment Block button in the toolbar:

Private Sub CommentEntireBlock()

    Sheet1.Range("A1").Value = "Test"

    If Sheet1.Range("A1") = "Test" Then
        MsgBox "The value of A1 cell is: Test"
    End If

End Sub

To enable keyboard shortcuts for commenting:

  • Right-click somewhere on empty space in the toolbar.
  • Choose Customize option and select the Edit under the categories.
  • Find Comment Block in the Commands and drag and drop it next to the existing icons in the toolbar.
  • Now you can see the newly added button in the toolbar
  • Click on the Modify Selection and check option Image and Text.
  • Click again on the Modify Selection and under Name add an ampersand (&) at the beginning of the name, so the name of the button is “&Comment Block”.

Now you can select a single line or a block of code and press Alt+C on your keyboard to comment.

To enable the same option for uncommenting a code, you can repeat the whole process for Uncomment Block command. The shortcut for uncommenting is ALT+U.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

When working with VBA coding in Excel, you can easily add comments while writing the code.

Comments in VBA could be really useful for beginners, where you can add a comment to a line of code (or a block of code) that explains what it does. So the next time you come back to the code, you’ll not be completely lost and would have some context because of the comments.

Even for advanced Excel VBA programmers, once the code starts to get beyond a few lines, it’s a good idea to add context using comments (especially if there is a chance that someone else may have to work on the code in the future)

And since it’s a comment, VBA ignores it while executing the code.

In this short Excel tutorial, I will cover how to add comments in VBA and all the best practices around it.

Adding Comments in VBA in Excel

To add a comment in VBA, simply add an apostrophe sign before the line that you want to be marked as a comment.

Anything after the apostrophe sign in that line would be considered a comment and VBA would turn it into green color (to visually differentiate it from regular code)

Comment in VBA Example

There are two ways you can add a comment in VBA:

  1. Have a comment in a separate line, where this line starts with an apostrophe and then has the comment text after itComment within the code in a separate line
  2. Have a comment as a part of the regular code line, where after the code you have a space character followed by an apostrophe, and then the comment(as shown below)Comment in the same line in the code

While I’ve seen both of these being used by the VBA programmers, I prefer the first method where a comment has a separate line altogether.

Another (old school) method of adding a comment is to have the word ‘Rem’ followed by the comment.

REM comment in Excel VBA

Here Rem is short for Remark.

Rem was used in the days of BASIC and has been kept in the current versions of VBA. While it’s good to know that it exists, I recommend you only use the apostrophe method while adding comments in VBA.

Converting a Line of Code (or Block of Code) into Comment

Sometimes, you may have a need to convert an existing line of code (or a block of code) into comments.

Programmers often do this when they’re working on a code and they want to quickly try out something else, while still keeping the already written code.

So you can quickly comment out a line, try a new one, and if you want to get the earlier code back, just remove the apostrophe and convert that comment back into a normal line of code.

For a line (or even a few lines), it’s best to manually add the apostrophe before these lines.

But if you have a large block of code, use the below steps to add the option to convert an entire block of code into a comment:

  1. Click the View tabClick the View option
  2. Go to the Toolbar option.
  3. When you hover your cursor over it, you’ll see more options
  4. Click on the Edit option. This will make the edit toolbar appear somewhere on your screen.Click on Edit
  5. Drag the Edit toolbars towards the toolbar area so that it would dock itself there (in case it’s not docked already)
  6. Select the block of code that you want to comment out
  7. Click on the ‘Comment Block’ option in the toolbarComment block icon in the toolbar

The above steps would instantly convert a block of code into comments by adding an apostrophe in front of every line in that code.

In case you want to remove the comment and convert it back into regular code lines, select that block of code again and click on the ‘Uncomment block’ option in the Edit toolbar

Changing the Color of the Comment in Excel VBA

While VB doesn’t allow a lot of formatting, it does allow you to change the color of the comment if you want to.

One of my VBA course students emailed me and told me that the ability to change the color of comments in VBA was really useful for people suffering from color blindness.

Below are the steps to change the color of the comment in Excel VBA:

  1. Open the Visual Basic Editor
  2. Click the Tools option in the menuClick the tools option in the menu
  3. Click on OptionsClick on Options
  4. In the Options dialog box, click on the ‘Editor Format’ tabSelect Editor Format tab
  5. In the Code colors options, select Comment TextSelect Comment Text option in the left pane
  6. Change the Foreground and/or the background colorChange the color
  7. Close the dialog box

When you change the comment color, it would also change the color for all the existing comments in your code.

Some Best Practices when Working with Comments in VBA

Here are some of the best practices to keep in mind when using comments in the VBA code.

  1. Keep the comment meaningful and add context. When adding a comment, consider what would be helpful for a new user who has never seen this code and is trying to make sense of it.
  2. Avoid excessive commenting as it would make your code look a bit cluttered. While it’s alright to add more comments when you are a beginner, as you gain more experience in VBA coding, you would anyway not need to add a lot of comments.
  3. For every new Subroutine or Function, it’s a good idea to add a comment that explains what it does.
  4. When working with complex code, it’s a good idea to add comments before conditions and loops, so that it’s easier for you to get a handle on what you had done when you revisit the code (or when someone else goes through the code)

In this tutorial, I covered how you can add comments in VBA and some best practices to use it.

I hope you found this tutorial useful.

Other Excel tutorials you may also like:

  • How to Insert / Delete Comments in Excel (including Shortcuts)
  • How to Print Comments in Excel
  • Get a List of All the Comments in a Worksheet in Excel
  • Working with Worksheets using Excel VBA
  • Using Workbook Object in Excel VBA (Open, Close, Save, Set)
  • Useful Excel Macro Examples for VBA Beginners (Ready-to-use)
Skip to content

How to Use Comments in Excel’s VBA Editor

How to Use Comments in Excel’s VBA Editor

Written by co-founder Kasper Langmann, Microsoft Office Specialist.

Like any scripts, Excel’s VBA modules can be very long and complicated to read.

Basic VBA scripts are easy to work your way through.

But once you start adding more variables and functions, it gets very difficult to figure out what’s going on.

So, how do you keep your VBA code organized?

And make it clear what the various parts of the file actually do?

With comments!

Let’s take a look at how to insert comments, and then talk about what you should use them for.

Kasper Langmann, Co-founder of Spreadsheeto

How to insert comments in VBA code

Inserting comments in Excel’s VBA code is as simple as inserting an apostrophe.

If there’s an apostrophe at the beginning of a line, it will be “commented out.”

excel-vba-comment

What happens when a line is commented out?

Excel completely ignores it when it’s running the VBA code. So you can type whatever you want.

We’ll talk about what sort of information you may want to put in comments in a moment.

You’ll know that a line has been commented out when the text is green.

Open up the Visual Basic Editor in Excel (click the Visual Basic button in the Developer tab) and try it yourself.

excel-funcres-vba

You can add a new line and prepend an apostrophe, or just add an apostrophe to an existing line.

Adding an apostrophe to an existing line might change how the VBA runs—or even break it completely.

We’ll talk about why you might want to do that in a moment.

Kasper Langmann, Co-founder of Spreadsheeto

What to use VBA comments for

Now that we’ve seen how to add comments to Visual Basic in Excel, let’s talk about why you’d use them.

As I mentioned, VBA code can get very complicated very quickly.

If you’re working on a script over a long period of time (or even coming back later to tweak it), you might find that it’s very unclear.

excel-vba-macro-example

Comments can solve that problem.

Many programmers recommend adding comments before each section of the code to remind yourself (or whoever’s editing the code) of what the next block does.

excel-vba-comment-explanation

This makes editing—no matter who’s doing it—significantly easier.

That isn’t to say that you should leave a comment before every line. In many cases, it’s clear what the code is doing.

Kasper Langmann, Co-founder of Spreadsheeto

You can also use comments to prevent Excel from executing certain lines without deleting them.

This is great for when you’re testing different scripts to see if they get you the result you want.

In this example, I’ve commented out a line of viable code:

excel-vba-comment-out-code

This lets me run the script and see what happens if that line isn’t included.

If I decide that I want to reinsert that line, all I have to do is delete the apostrophe at the beginning of the line. It’s much easier than trying to remember what was there in the first place.

When you comment out code, it’s a good idea to leave a comment before it saying why you did so you don’t forget later.

Kasper Langmann, Co-founder of Spreadsheeto

When in doubt, leave a comment

It’s not always clear exactly when you should leave a comment in your code. But in general, it’s better to leave one than not.

I don’t recommend going crazy and leaving a comment on everything.

It’s better to include more information than less, but too many comments can make a file harder to work with than no comments at all.

Think about it from the perspective of someone coming back to this file a year from now. What will they need to know?

Kasper Langmann, Co-founder of Spreadsheeto

Kasper Langmann2023-02-23T15:21:51+00:00

Page load link

Содержание:

  1. Добавление комментариев в VBA в Excel
  2. Преобразование строки кода (или блока кода) в комментарий
  3. Изменение цвета комментария в Excel VBA
  4. Некоторые рекомендации при работе с комментариями в VBA

При работе с кодированием VBA в Excel вы можете легко добавлять комментарии во время написания кода.

Комментарии в VBA могут быть действительно полезны для новичков, где вы можете добавить комментарий к строке кода (или блоку кода), объясняющий, что он делает. Так что в следующий раз, когда вы вернетесь к коду, вы не потеряетесь полностью и у вас будет какой-то контекст из-за комментариев.

Даже для продвинутых программистов Excel VBA, как только код начинает выходить за пределы нескольких строк, рекомендуется добавлять контекст с помощью комментариев (особенно если есть вероятность, что кто-то другой, возможно, придется поработать над кодом в будущем)

А поскольку это комментарий, VBA игнорирует его при выполнении кода.

В этом коротком руководстве по Excel я расскажу, как добавлять комментарии в VBA, и расскажу обо всех передовых методах, связанных с этим.

Добавление комментариев в VBA в Excel

Чтобы добавить комментарий в VBA, просто добавьте знак апострофа перед строкой, которую вы хотите пометить как комментарий.

Все, что находится после знака апострофа в этой строке, будет считаться комментарием, и VBA превратит его в зеленый цвет (чтобы визуально отличить его от обычного кода)

Добавить комментарий в VBA можно двумя способами:

  1. Добавьте комментарий в отдельной строке, где эта строка начинается с апострофа, а после него следует текст комментария.
  2. Добавьте комментарий как часть обычной строки кода, где после кода у вас есть пробел, за которым следует апостроф, а затем комментарий (как показано ниже)

Хотя я видел, что оба они используются программистами VBA, я предпочитаю первый метод, при котором комментарий имеет отдельную строку.

Другой (старый) метод добавления комментария состоит в том, чтобы за комментарием следовало слово «Рем».

Здесь Рем — сокращение от Remark.

Rem использовался во времена BASIC и сохранился в текущих версиях VBA. Хотя хорошо знать, что он существует, я рекомендую вам использовать только метод апострофа при добавлении комментариев в VBA.

Преобразование строки кода (или блока кода) в комментарий

Иногда вам может потребоваться преобразовать существующую строку кода (или блок кода) в комментарии.

Программисты часто делают это, когда работают над кодом и хотят быстро опробовать что-то еще, сохраняя при этом уже написанный код.

Таким образом, вы можете быстро закомментировать строку, попробовать новую, и, если вы хотите вернуть предыдущий код, просто удалите апостроф и преобразуйте этот комментарий обратно в обычную строку кода.

Для строки (или даже нескольких строк) лучше вручную добавить апостроф перед этими строками.

Но если у вас большой блок кода, используйте следующие шаги, чтобы добавить опцию преобразования всего блока кода в комментарий:

  1. Перейдите на вкладку «Просмотр».
  2. Перейдите к опции панели инструментов.
  3. Когда вы наведете на него курсор, вы увидите больше вариантов.
  4. Нажмите на опцию Edit. Панель инструментов редактирования появится где-нибудь на экране.
  5. Перетащите панели инструментов редактирования в область панели инструментов, чтобы они закрепились там (в случае, если они еще не закреплены).
  6. Выберите блок кода, который вы хотите закомментировать
  7. Нажмите на опцию «Блок комментариев» на панели инструментов.

Вышеупомянутые шаги мгновенно преобразовали бы блок кода в комментарии, добавив апостроф перед каждой строкой в ​​этом коде.

Если вы хотите удалить комментарий и преобразовать его обратно в обычные строки кода, выберите этот блок кода еще раз и нажмите на опцию «Uncomment block» на панели инструментов Edit.

Изменение цвета комментария в Excel VBA

Хотя VB не допускает большого форматирования, он позволяет при желании изменить цвет комментария.

Один из моих студентов курса VBA написал мне по электронной почте и сказал, что возможность изменять цвет комментариев в VBA действительно полезна для людей, страдающих дальтонизмом.

Ниже приведены шаги по изменению цвета комментария в Excel VBA:

  1. Откройте редактор Visual Basic
  2. Выберите в меню пункт Инструменты.
  3. Нажмите на Параметры
  4. В диалоговом окне «Параметры» перейдите на вкладку «Формат редактора».
  5. В параметрах цветов кода выберите Текст комментария.
  6. Измените цвет переднего плана и / или фона
  7. Закройте диалоговое окно

Когда вы меняете цвет комментария, он также изменяет цвет для всех существующих комментариев в вашем коде.

Некоторые рекомендации при работе с комментариями в VBA

Вот несколько рекомендаций, которые следует учитывать при использовании комментариев в коде VBA.

  1. Сделайте комментарий содержательным и добавьте контекст. Добавляя комментарий, подумайте, что было бы полезно для нового пользователя, который никогда не видел этот код и пытается разобраться в нем.
  2. Избегайте чрезмерного комментирования, так как это может сделать ваш код немного загроможденным. Если вы новичок, то можете добавлять больше комментариев, но по мере того, как вы набираетесь опыта в кодировании VBA, вам все равно не нужно будет добавлять много комментариев.
  3. Для каждой новой подпрограммы или функции рекомендуется добавлять комментарий, объясняющий, что они делают.
  4. При работе со сложным кодом рекомендуется добавлять комментарии перед условиями и циклами, чтобы вам было легче понять, что вы сделали, когда вы повторно просматриваете код (или когда кто-то другой просматривает код)

В этом уроке я рассказал, как можно добавить комментарии в VBA и некоторые рекомендации по его использованию.

Надеюсь, вы нашли этот урок полезным.

VBA Macro is for developers. Macro is a piece of code written in VBA. VBA is Microsoft’s programming language and it stands for Visual Basic for Applications. Let’s see how to set up our VBA Macro and how to add comments in a VBA in Excel.  

VBA Macro

Excel is a very advanced tool that contains thousands of functionalities, but VBA Macro comes into existence when we have to do a repeated task. The complex repeated tasks can be automated with the help of VBA Macro. 

Initial Set-Up

Go to Developer Tab. We will see that by default developer tab is not present in the menu bar. 

No-developer-tab

Follow the steps: 

Step 1: Right-click on any tab in the menu bar. Click on Customize the Ribbon. A dialogue box appears. 

Customizing-the-ribbon

Step 2: In the Mains Tab, check the box Developer and click on Ok.

Checking-box-developer

Step 3: Now the Developer Tab is visible. 

Visible-developer-tab

Step 4: Go to Developer Tab and click on Visual Basic. 

Clicking-developer-tab

Step 5: Now, the VBA tab is opened. Click on Tools in the menu bar and then click on Macros. A dialogue box is open. 

Dialogue-box-opening

Step 6: Write the macro name and click on create. 

Creating-macro-nameSub-macro-created

A Macro is created. 

VBA Comments

Comments are the lines in the code that are ignored while executing the code. These are represented as green text in the code. The comments help describe the written code. Knowing the correct use of comments is very important because while working with long and complex code, comments help us identify which part of code does what. It is very helpful for development purposes. 

Adding Single Line comment in VBA

Step 1: Click on the line where you want to insert a comment. 

Inserting-comment

Step 2: Type an Apostrophe( ‘ ) at the start of a line. 

Typing-apostrophe

Step 3: Write the comment you want. 

Writing-comment

Step 4: Press Enter and you fill find the comment written to be green. 

Comment-shown-in-green

Adding Multi-Line comment in VBA

We can add comments in multiple lines. We use multi-line comments when we have to add points in our description or the description is long. 

Step 1: Keep your cursor on the Tool Bar. 

Reaching-toolbar

Step 2: Right-click on the Tool Bar and click on edit. An extended Tool Bar appears. Drag and place it in the already existing Tool Bar. 

Editing-in-toolbarExtended-toolbar

Step 3: Select the text you want to comment on and click on Comment Block. 

Selecting-comment

The entire selected text got commented. 

Selected-text-commented

Using Buttons to add a comment

Step 1: Go to Toolbar and right-click on it. A menu appears. 

Clicking-on-toolbar

Step 2: Click on Customize and a dialogue box appears. 

Dialogue-box-appears

Step 3: Go to edit in the left-side scrollable list. 

Editing-in-customize

Step 4: Find Comment Block and Uncomment Block in the right-side scrollable list.

Editing-scrollable-list

Step 5: Click on Comment Block and drag it to the menu bar. It will look like a button in the menu bar. 

Clicking-comment-block

Step 6: Click on Uncomment Block and drag it to the menu bar. It will look like a button in the menu bar. 

Clicking-uncomment-block

Step 7: With the dialogue box opened. Go to the comment block and right-click on it. A menu appears.

menu-appears

Step 8: Click inside the Name and add a character & at the starting of Comment Block. Then click somewhere outside the appeared menu. 

Adding-character

Step 9: Again, right-click on the Comment Block and select Image and Text.

Selecting-image-and-text

Step 10: Repeat steps 7, 8, 9 for Uncomment Block i.e. right-click on the Uncomment Block and add & in the Name. Also, select the Image and Text in the appeared menu. At last, close the dialogue box. 

Adding-character-in-nameEditing-image-and-text

Step 11: A shortcut for comment and uncomment has been created in the VBA code editor. To comment on a line the shortcut is Alt + C and to uncomment a line the shortcut is Alt + U. You can also use the Comment Block and Uncomment Block buttons to comment on a line. Enter the text you want to comment on. 

Editing-text

Step 12: To comment on the written line. You can click Alt + C.

Commenting-on-written-line

Step 13: To uncomment a line, you can press Alt + U. 

Uncommenting-a-line

Use Rem to Comment

At the start of the comment use the keyword Rem to comment on a line. 

Commenting-a-line

Formatting Comments 

Step 1: Go to Tools Tab, and right-click on it. 

clicking-tools-tab

Step 2: A menu appears, and click on Options… A dialogue box appears. 

Clicking-options

Step 3: Go to Editor Format.

Opening-editor-format

Step 4: Select the Comment Text from the left scrollable list. 

Selecting-comment-text

Step 5: You can change the color of the comment by selecting Foreground. For example, red. Click Ok

Changing-color

Step 6: Now, all comments will have a font color of red. 

Red-color-added

How To Insert A VBA Comment/Note

Microsoft’s VBA coding language allows you to create non-executable lines of code for commenting or note-taking. Incorporating comments into your VBA macro code is almost as important as the code itself. These notations will allow you to remember the purpose of your code and help others understand your thought process while troubleshooting or modifying your VBA macro in the future.

VBA has the simplest way to convert a line of code into a comment. You simply need to place an apostrophe in front of the text you wish to turn into non-executable code, and the remaining text in that line will turn into a comment.

You’ll visually see that your VBA code has turned into a comment as it will change its font color to green after you navigate to a different or new line in your code. Many people have gotten confused by the fact that the comment format does not change until after you click off of the commented line.

Adding Comments Beside Code

As an alternative to creating entire lines of commented text, you also have the capability to place comments to the side of your code. This may be practical if you want to notate an alternate value to a variable input or if you have a comment that is only a few words.

The only stipulation to adding a comment next to your VBA code is the remainder of the code line will be commented. You cannot have comments stuck in between code on the same line.

Comment A Section Of Code At Once

There may be times when you are writing your code that you wish to prevent or turn off a section while testing. This typically would require you to insert an apostrophe character in front of each line of the code you wish to turn off. 

The problem with this is if you have many lines of code that you are wanting to comment out, this could take quite a lot of manual work (especially if you are needing to go back and forth between each state).

Luckily, Microsoft’s Visual Basic Editor has a toolbar button that will allow you to comment out an entire selection of text with just one click. This button is called the Comment Block button and it resides in the Edit toolbar.

By default, the Edit Toolbar may not be visible in your Visual Basic Editor. To ensure you have access to it, navigate to the View menu, select the Toolbars menu button and ensure that the Edit button has a check next to it (click it if it doesn’t).

The Comment Block button is the 9th button in the Edit Toolbar. By clicking the Comment Block button, any code you have selected will automatically be commented by inserting an apostrophe in front of each line of text.

NOTE: The Comment Block button only places an apostrophe at the beginning of a code line. If you attempt to select part of a line, the entire code line will be commented out.

Remove Comments From A Section of VBA Code

It would not be fair if you can add comments to a large section of code all at once and not remove the comments in a similar fashion. That would just be cruel and unusual punishment!

To remove all the apostrophes from the beginning of your selected code lines, you can click the Uncomment Block button. This button is right beside the Comment Block button in the Edit Toolbar.

NOTE: The Uncomment Block button only removes the apostrophes from the beginning of code lines. If you have comments beside VBA code on the same line, that comment’s apostrophe will not be removed by the Uncomment Block button.

Create A Multi-Line Comment

While not very common, there is a way to create a multi-line comment. This technique is virtually identical to how you write multi-lined VBA code.

By inserting a space + underscore at the end of your commented code, you indicate that you would like the following line to also be part of the same commented text. You can repeat this as many times as you’d like to create multi-lined notes with the use of a single apostrophe character.

Change The Color Format Of VBA Comments

By default commented text is a green color. If you would like to change this in your Visual Basic Editor (this does not get passed along to others), you can do the following:

  1. Open the Tools menu in the Visual Basic Editor

  2. Click Options…

  3. Navigate to the Editor Format Tab

  4. In the Code Colors Listbox, select Comment Text

  5. Modify your desired color formats

    • Foreground Color represents the font text color

    • Background Color represents the fill color behind the text (like a highlight)

  6. Click the OK button

Creating Keyboard Shortcuts For Commenting

Unfortunately, there are no out-of-the-box keyboard shortcuts set up for the Comment Block and Uncomment Block buttons. There are, however, toolbar customizations you can tweak to assign a keyboard shortcut to these functions.

The concept behind assigning keyboard shortcuts in the Visual Basic Editor is renaming buttons with an “&” symbol along with a letter. This translates to the keyboard shortcut Alt + [insert your letter].

For example, we could rename the Comment Block button to be titled &C which would allow us to call that button’s functionality with the keyboard shortcut Alt + C.

How To Customize A Toolbar Button In The VBE

Let’s walk through how to customize the Comment Block button so that it has a keyboard shortcut that we can call.

  1. Right-click on a toolbar button and select Customize…

  2. Select the Comment Block button so that it has a thick black box around it

  3. Select the Commands tab

  4. Click the Modify Selection menu button

  5. Place and “&” character at the beginning of the Name field along with a letter you wish to include as the shortcut key

  6. Select the Image and Text menu item so that it has a checkmark beside it

  7. Close out of the Customize dialog box

Now you should see your Comment Block button modified. You will not see the “&” character you entered into the Name Field. Instead, you will see the first character in the button name underlined. This indicates that the button now has a keyboard shortcut assigned to it.

In this example, the keyboard shortcut is Alt + C.

If you don’t want too much text showing in your toolbar, you can forgo the full label and just include the shortcut letter. In the above example, I used “&C” and “&U” as my button label text so that my toolbar didn’t have too much text in it.

I Hope This Helped!

Hopefully, I was able to explain how you can use VBA commenting within your macro code. If you have any questions about this technique or suggestions on how to improve it, please let me know in the comments section below.

About The Author

Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.

Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you with some value today and I hope to see you back here soon! — Chris


Commenting on a code means inserting information inside the VBE that will not be executed (the information is used for guidance only).

This practice has some advantages:

  • It helps other users to understand the code, saving time on explanations
  • It helps to remember the purpose of a particular code
  • It prevents Excel from executing unwanted parts of the code when testing it

To comment on a code just use a simple apostrophe symbol. Everything that comes after the sign will be considered a comment:

    'This is a comment

We can also apply it to parts of the code to temporarily disable them:

Sub Comment()

    'MsgBox "This will not run"
    MsgBox "But this will run"

End Sub

When executing, the following text box should appear:

VBA Comment

A comment may also be inserted into the same line after a code that will be executed.

Sub CommentAfter()

    MsgBox "This will be shown" 'And this comment will not interfere

End Sub

After the apostrophe, the rest of the line will become comment.


Commenting on a Code Block

Edit Tab

With the Edit Toolbar you can insert and remove comment blocks, just underline the code and use the buttons: Comment block and Uncomment block .

    'Sub CommentBlock()
    '
    '    MsgBox "This will not be shown" 'And this comment will not interfere
    '
    'End Sub

To add the Edit Toolbar in VBE go to: View $rightarrow$ Toolbars $rightarrow$ Edit.


Important Shortcuts in VBA Excel

Some shortcuts that will help save time:

Shortcuts that will only work in the VBE environment:



SuperExcelVBA.com is learning website. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. All Rights Reserved.

Excel ® is a registered trademark of the Microsoft Corporation.

© 2023 SuperExcelVBA | ABOUT

Protected by Copyscape

Понравилась статья? Поделить с друзьями:
  • Visual basic excel диапазон
  • Visual basic studio 2010 excel
  • Visual basic excel дата
  • Visual basic project in excel
  • Visual basic excel выпадающий список