Vba excel комментарии в коде

Содержание:

  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 и некоторые рекомендации по его использованию.

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

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!

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

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

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

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)

Comments in VBA programming are statements that are not executed or compiled but are only there to provide a brief description of any function, variable, statement, etc. These comments are not mandatory but are used to make the blocks of VBA code more informative, readable, organized, and easy to understand. Also, if we do not wish to delete certain lines of code and neither want them to execute, we can comment on them.

Table of contents
  • Excel VBA Comment Block of Code
    • How to Comment on Block of VBA Code?
      • Example #1 – Comment using Apostrophe
      • Example #2 – Using Toolbar
        • Step 1: Select the Statements from code.
        • Step 2: Click on View -> Toolbars -> Customize
        • Step 3: From Customize Window Click on Commands -> Edit, then select Comment Block
      • Example #3 – Using REM Keyword
      • Example #4 – UnComment the Commented lines using Toolbar
    • Things to Remember
    • Recommended Articles

VBA Comment Block

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Comment Block (wallstreetmojo.com)

How to Comment on Block of VBA Code?

You can download this VBA Block Comment Template here – VBA Block Comment Template

We wish to comment on a single line/statement/block in a VBA code. We must configure the Visual Basic Editor (VBE) to do this.

The Visual Basic Editor can be accessed as follows:

First, go to the Excel Developer tabEnabling the developer tab in excel can help the user perform various functions for VBA, Macros and Add-ins like importing and exporting XML, designing forms, etc. This tab is disabled by default on excel; thus, the user needs to enable it first from the options menu.read more, click “Visual Basic Editor,” or press Alt+F11 to open the “Visual Basic Editor” window.

VBA Block Comment Example 1

In doing this, a window opens as follows:

VBA Block Comment Example 1-1

Right-click on the workbook name in the “Project-VBAProject” pane and then click on “Insert” -> “Module” as follows.

VBA Block Comment Example 1-2

Now, we can write our code or procedure in this module:

Code:

Sub macro()

 'This is a Comment

End Sub

VBA Block Comment Example 1-3

So, we can see in the above screenshot that when writing this code in the module, when we put or insert an apostrophe before a statement/line, that statement turns into green text and is considered a comment. So, we see that when we wish to comment on a single line, it can precede us with an apostrophe.

We can also use this method to comment on multiple lines by putting an apostrophe before each line as follows:

VBA Block Comment Example 1-4

Example #2 – Using Toolbar

Suppose we wish to skip over and comment on an entire block of code or multiple statements of the code. In such a case, using an apostrophe before each statement would be tedious and time-taking when we have so many statements to comment on. So to do this, there is a built-in option of “Comment/Uncomment Block” in VBA,  initially hidden in the toolbar, and we can use it as follows:

Step 1: Select the Statements from code.

Select the statements in the macro/procedure that must comment below.

VBA Block Comment Example 2

Step 2: Click on “View” -> Toolbars -> Customize

VBA Block Comment Example 2-1

Step 3: From “Customize” Window Click on “Commands” -> Edit, then select “Comment Block”

It will generate or open a “Customize” pop-up window. Now, click on “Commands” -> “Edit” and then click on “Comment Block” and drag it to the toolbar.

VBA Block Comment Example 2-2

With this, we now have the “Comment Block” icon on the toolbar for easy access.

Now, click on the “Comment Block” from the toolbar as follows:

VBA Block Comment Example 2-3

In doing so, the highlighted statements/lines would now be commented and turn out to be green in color as below:

Code:

Sub CommentLines()

 'MsgBox "First Comment Line"
 'MsgBox "Second Comment Line"
 'MsgBox "Third Comment Line"

End Sub

VBA Block Comment Example 2-4

So, we can see in the above screenshot that the green statements will not execute by the macro and will only be treated as comments blocks.

Example #3 – Using REM Keyword

Another method we can use to make a statement/line as a comment is adding the keyword ‘REM’ before it.

Let us see below how this works:

VBA Block Comment Example 3

We can see in the screenshot below that when we add the keyword “REM” before the statement: “This is a comment,” it turns out to be green and hence a comment.

VBA BlockComment Example 3-1

Now, let us see how we can use this keyword to comment on multiple lines in the below screenshot.

Code:

Sub CommentUsingRem()

 Rem This is a Comment
 Rem This is a Comment
 Rem This is a Comment

End Sub

VBA BlockComment Example 3-2

So, we can see that apart from using apostrophes and “Comment Block,” the keyword we can also use “REM” to comment statements of code or procedure. However, using the keyword “REM” has some limitations:

  • Space is mandatory between the keyword “REM”and the start of the statement.
  • It always has to be the first word to start with and cannot be used somewhere in the middle of a line/statement to comment on the rest of the line.

Just the way we can comment a block of lines at one go, we can also uncomment the commented lines using the VBE built-in “Uncomment Block” option in the same way as follows:

Select the commented statements in the macro/procedure that we require to uncomment as below:

Block Comment Example 4

Now, select View -> Toolbars -> Customize.

Example 4-1

It will generate or open a “Customize” pop-up window. Now, click on Commands -> Edit, and then click on Uncomment Block and drag it to the toolbar as follows:

Example 4-2

With this, we now have the “Uncomment Block” icon on the toolbar for easy access.

Now click on the “Uncomment Block” from the toolbar as follows:

Example 4-3

For doing that, the highlighted statements that commented would now turn into executable statements of the code or procedure and change in color from green to black again as below:

Code:

Sub UncommentedLines()

 MsgBox "First Comment Line"
 MsgBox "Second Comment Line"
 MsgBox "Third Comment Line"

End Sub

VBA BlockComment Example 4-4

So, these statements are no longer comments.

Things to Remember

  • Comments are brief explanatory statements that we can use to describe the procedures.
  • Commenting can be useful in debugging the codes.
  • Any statement in the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more that follows an apostrophe is considered a comment.
  • As a good programming practice, comments can be used before each code section or variable declarations and functions to describe their purpose.
  • The VBA EditorThe Visual Basic for Applications Editor is a scripting interface. These scripts are primarily responsible for the creation and execution of macros in Microsoft software.read more makes the statement’s font color green to indicate that it is a comment.
  • The compiler ignores the statement following an apostrophe until the end of the line, unless the apostrophe is present in a string.
  • An apostrophe can even be present somewhere in the middle of a line. Text after the apostrophe will be treated as a comment in that case.

The following screenshot illustrates this:

Apostrophe Comment

  • The comments do not affect code performance.
  • The comment symbol: Apostrophe’, or “REM,” has to be used on each line if the comments require more than one line.
  • By default, the comments appear as green in the code window.
  • The advantage of using apostrophes and “Comment Block” over the keyword “REM” is that they need less memory and space and are also easier to use.

Recommended Articles

This article has been a guide to VBA Comment Block. Here, we learn three ways to comment blocks of VBA codes using 1) Apostrophe, 2) Toolbar, 3) REM keyword, practical examples and a downloadable Excel template. Below you can find some useful Excel VBA articles: –

  • VBA Workbook Open
  • VBA RegEx
  • VBA Workbook Object

Dear Friends,

This is a very simple yet useful article, especially for beginners. Sometimes even intermediate-level users also do not know about all these options to comment on a line or group of lines in Excel VBA.

Like every other programming language, VBA too has an option to comment on a line or group of lines in your code.
For those who does not know – what is comment in a Programming:

Commenting a line or group of lines in any programming language means – to instruct the execution control or compiler to skip those lines from compilation or execution.

Before I tell you how to comment on a line in Excel VBA, let me explain to you – the use of it

What is the use of comments in Excel VBA Programming

As mentioned above these comments is something that is not compiled or executed, a programmer can write anything in any simple human language to give a brief description of a function, a variable, a statement, etc.
This makes the programmer’s life easier from a maintenance perspective. By reading those brief descriptions of the code, any programmer can have a basic idea of what that function or statement or variable, etc. does.

It is not MANDATORY but a good programming practice to provide proper comments so that any other programmer can easily understand the code easily.

How to comment a single line in VBA code

Basically, there are 3 ways to do so.

Method 1: Using Single Quote (‘)

This is one of the simplest methods to comment on a single line in VBA programming.
To comment on a line, you can simply type a single quote (‘) at the beginning of that line. The whole line will turn into green text. That’s all!
Now that line would neither be compiled nor executed.

To Comment a line in VBA

To Comment a line in VBA

Note:

A single quote can be put somewhere in the middle of a line as well. In such case, rest of the text after the single quote (‘) will be treated as comment.
Refer to the below image

Comment Line in VBA

Comment Line in VBA

Method 2: Using REM Keyword in Excel VBA

This is also a simple one but I do not prefer this. You can see the reason below in the note section.

To comment on any line in VBA you can start that line with the keyword REM So in this method, instead of a single quote (apostrophe) you can type the Rem keyword.

Rem Keyword to comment a line

Rem Keyword to comment a line

Note:

Following are the limitation using this Rem keyword
1. There should be at least one space between the start of your comment and the Rem keyword.
2. Like a single quote, the Rem keyword can not be used in the middle of a line to comment rest of the line. Rem keyword must always be the first word to start with.

I think the above two reasons are more than enough for me not to like it :).

Method 3: VBE built-in Option – Comment/Uncomment Block

This is the same method as the first one, but here you do not need to type a Single quote by yourself, rather you can follow the below steps:
1. Place your mouse cursor anywhere on the line on which you want to comment
2. Press on “Comment” button as shown in below video

Toggle between comment and un-comment

Toggle between comment and un-comment

Important:

Using this method you also get an option to press the “Uncomment” button as well as shown in the above gif video.

How to comment or un-comment multiple lines together

Unfortunately in VBA, there is no shortcut key to do so. But don’t worry, method 3 is very useful in this case.
You can use the same buttons Comment Block and Un-comment Block to do this.
Simply select all the lines you want to comment on or uncomment it and press the relevant button as shown below:

1# How to comment group of lines (Block) in VBA

Step 1: Select all the lines (block)
Step 2: Press the Comment Block as shown in above picture

Comment Uncomment VBA Methods

Comment Uncomment VBA Methods

2# How to Un-comment group of lines (Block) in VBA

Step 1: Select all the commented lines (block)
Step 2: Press the Uncomment Block as shown in above picture

Comment Uncomment VBA Methods

Comment Uncomment VBA Methods

What if Comment Block and Uncomment Block Button not visible

Follow the below steps:
Step 1: Go to View –> Toolbars –> Edit

VBE - View Edit Option

VBE – View Edit Option

Step 2: Check the Edit option. You will see the Edit toolbar where you can find these two options along with others.

Comment-uncomment-button

Comment-uncomment-button

Like this post? Please share to your friends:
  • Vba excel команда если
  • Vba excel команда for
  • Vba excel колонка ячейки
  • Vba excel коллекция файлов
  • Vba excel коллекция уникальных значений