Excel vba макросы комментарии

Содержание:

  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

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)

Понравилась статья? Поделить с друзьями:
  • Excel vba макрос при сохранении
  • Excel vba макрос при открытии листа
  • Excel vba макрос при изменении ячейки
  • Excel vba макрос при выборе листа
  • Excel vba макрос при активации листа