Sunday, February 16, 2025
No menu items!
HomeData Analytics and Visualization4 Ways to Add Comment in VBA Code

4 Ways to Add Comment in VBA Code

This tutorial explains how to add comments in VBA code.

Comments are used to add explanations or notes within the code. They do not affect the execution of the code as the VBA compiler ignores such comments.

1. Using Single Quote (‘) Symbol

Anything following the single quote is considered a comment and will not be executed as part of the code. If we want to comment multiple lines then we need to add the single quote (‘) at the start of each line.

' This is a comment

We can also add comment at the end of a line of code.

Dim num As Integer  ' Declare an integer variable
2. Using REM method

REM stands for “Remark”. Anything that follows ‘REM’ on that line is treated as a comment. We must use a space after REM and then begin writing our comment.

REM This is a comment
3. Comment Code Block Manually

We can follow the procedure below to comment a code block :

  1. Highlight the Lines : Highlight by clicking and dragging or by holding down Shift and using the arrow keys to select the lines.
  2. Use the Comment Block Button : The “Comment Block” button is located in the toolbar at the top of the VBA editor.
Enable “Comment Block” button
  • Press : View > Toolbars > Edit
4. Insert Line Method

The following code can be used to add comment “VBA code to remove filters” at second position in the ‘module1’:

Sub AddCommentToCode()

    Dim vbComp As Object
    Dim codeLine As String
    Dim comment As String
        
    Set vbComp = ThisWorkbook.VBProject.VBComponents("Module1")
   
    codeLine = "VBA code to remove filters"
    
    vbComp.CodeModule.InsertLines 2, "'" & codeLine

End Sub

Press Run or F5 to run the above macro.

It has added the comment in the module 1 as shown in the image below.

VBA : Insert Line in a code using VBA

Read MoreListenData

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments