Excel vba закомментировать блок

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

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

Содержание:

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

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

0 / 0 / 0

Регистрация: 15.02.2009

Сообщений: 12

1

22.02.2009, 10:01. Показов 111371. Ответов 11


Студворк — интернет-сервис помощи студентам

как VBA закомментировать сразу несколько строк, чтоб каждую не начинать ковычками?



0



Vasya Pupkin

22.02.2009, 10:15

2

В редакторе VBA —
Вид -> Панели интрументов -> Правка -> Там есть две кнопочки 1. Закоментировать блок 2. Раскоментировать блок
Выделяешь необходимое кол-во строк и жмёшь…..

Это ли тебе нужно?

0 / 2 / 3

Регистрация: 27.03.2012

22.02.2009, 10:16

3

никак, это особенность языка



0



0 / 0 / 0

Регистрация: 15.02.2009

Сообщений: 12

22.02.2009, 14:45

 [ТС]

4

сама уже не знаю. что мне нужно… но за совет спавибо
хотелось просто закомментировать как-нибудь так :
/*
bla
bla
bla
*/



0



master-neo

26.07.2011, 17:28

5

Да, действительно чтобы сделать многострочный комментарий нужно поступить как сказал Вася Пупкин.

Разве нельзя за столько лет дополнить поддержку многострочных комментариев. Для кого язык сделан? Кто на нем будет программировать через несколько лет?
Обходиться формулами?

BioRenGen

Заблокирован

14.01.2019, 20:56

6

прошло уж 8 лет, а косяки остались)



0



es geht mir gut

11264 / 4746 / 1183

Регистрация: 27.07.2011

Сообщений: 11,437

14.01.2019, 21:48

7

Цитата
Сообщение от BioRenGen
Посмотреть сообщение

прошло уж 8 лет, а косяки остались)

Какие косяки ?

Excel 2007

Миниатюры

Как VBA закомментировать сразу несколько строк?
 



5



es geht mir gut

11264 / 4746 / 1183

Регистрация: 27.07.2011

Сообщений: 11,437

14.01.2019, 21:49

8

Это быстрее и удобнее, чем теги ставить.



0



4038 / 1423 / 394

Регистрация: 07.08.2013

Сообщений: 3,541

14.01.2019, 21:58

9

всегда делал сначала вот так



2



es geht mir gut

11264 / 4746 / 1183

Регистрация: 27.07.2011

Сообщений: 11,437

14.01.2019, 22:00

10

Не по теме:

snipe, что там в архиве ? Скачивать неохота



0



4038 / 1423 / 394

Регистрация: 07.08.2013

Сообщений: 3,541

14.01.2019, 22:01

11

маленький видос как вытащить эти кнопки что на рисунке



1



0 / 0 / 0

Регистрация: 13.11.2020

Сообщений: 1

15.11.2021, 17:05

12

snipe, Спасибо



0



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!

Рис.1. Добавление тулбара в среду разработки Microsoft Visual Basic for Applications

Среда разработки макросов в Excel Microsoft Visual Basic for Applications, мягко говоря, не является самой удобной средой разработки. Сравнивать его с Visual Studio просто нельзя – это как сравнить текстовые редакторы Блокнот и Word. Но пользоваться Microsoft Visual Basic for Applications иногда нужно, потому приходится адаптироваться.

Столкнулся с необходимостью закомментировать порядка 20 строчек кода. Ставить знак ‘ в начале каждой строки очень не хочется, к тому же потом еще и раскомментировать нужно.

По умолчанию, панель с кнопкой комментирования кода отключена. Для начала нужно включить панель редактирования, для этого в меню View / Toolbars нужно отметить пункт Edit (Рис.1).

Рис.1. Добавление тулбара в среду разработки Microsoft Visual Basic for Applications

Рис.1. Добавление тулбара в среду разработки Microsoft Visual Basic for Applications

Для того, чтобы закомментировать несколько строк кода, нужно в появившемся тулбаре нажать на кнопку «Comment Block» (Рис.2)

Рис.2. Закомментировать несколько строк кода

Рис.2. Закомментировать несколько строк кода

Для раскомментирования строчек нужно нажать на соседнюю кнопку «Uncomment block».


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