Среда разработки макросов в 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
Для того, чтобы закомментировать несколько строк кода, нужно в появившемся тулбаре нажать на кнопку «Comment Block» (Рис.2)
Рис.2. Закомментировать несколько строк кода
Для раскомментирования строчек нужно нажать на соседнюю кнопку «Uncomment block».
Комментарии в тексте макроса начинаются с апострофа на каждой строчке программы, а существует возможность закомментировать сразу целый блок? Например, как в других языках — /*
— начало блока, */
-конец блока?
P.S. Я нашла ответ, что
в редакторе VBA на панели Edit есть кнопки Comment Block, Uncomment
Block
но я у себя не нахожу подобного:
задан 28 окт 2016 в 11:08
5
View
-> Toolbars
-> Customise
Commands tab
-> Edit menu
Две иконки- Comment Block
и Uncomment Block
.
Перетащите из в тулбар Edit menu
.
Profit.
ответ дан 28 окт 2016 в 11:14
0 / 0 / 0 Регистрация: 15.02.2009 Сообщений: 12 |
|
1 |
|
22.02.2009, 10:01. Показов 111435. Ответов 11
как VBA закомментировать сразу несколько строк, чтоб каждую не начинать ковычками?
0 |
Vasya Pupkin |
|
22.02.2009, 10:15 |
2 |
В редакторе VBA — Это ли тебе нужно? |
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 |
сама уже не знаю. что мне нужно… но за совет спавибо
0 |
master-neo |
|
26.07.2011, 17:28 |
5 |
Да, действительно чтобы сделать многострочный комментарий нужно поступить как сказал Вася Пупкин. Разве нельзя за столько лет дополнить поддержку многострочных комментариев. Для кого язык сделан? Кто на нем будет программировать через несколько лет? |
Заблокирован |
|
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 |
прошло уж 8 лет, а косяки остались) Какие косяки ? Excel 2007 Миниатюры
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.
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!
Learn More!
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
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
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
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
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
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
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
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