4 Ways to Add Comment in VBA Code

Yash Gaur Add Comment

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 Block

We can follow the steps below to comment out the entire code at once :

Enable "Comment Block" button
  • Press : View > Toolbars > Edit
Comment Block

Select the entire code which you want to comment out and then hit the "Comment Block" button which is located in the toolbar at the top of the VBA editor.

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
Related Posts
Spread the Word!
Share
About Author:
Yash Gaur

Yash is pursuing an MBA in Finance with a keen interest in analytics. He enjoys working with data and leveraging his research and analytical skills to generate valuable insights.

Post Comment 0 Response to "4 Ways to Add Comment in VBA Code"
Next → ← Prev