• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

How to comment and uncomment some lines using vba code

alex gomes

New Member
I want uncomment some line of codes(line no 5 to 10) in "abc" module and put a break point in one line(suppose line no 7) ,then i want to remove the break point from the line and comment the lines again.

How to achieve this by using vba code?
 
Yes - the basic code is:
Code:
Sub CommentLines1to5()
    Dim n As Long
    With ThisWorkbook.VBProject.VBComponents("abc").CodeModule
        For n = 1 To 5
            .ReplaceLine n, "'" & .Lines(n, 1)
        Next n
    End With
End Sub
Sub UncommentLines1to5()
    Dim n As Long
    With ThisWorkbook.VBProject.VBComponents("abc").CodeModule
        For n = 1 To 5
            .ReplaceLine n, Mid$(.Lines(n, 1), 2)
        Next n
    End With
End Sub

Note that:
- You must have trusted access to the Visual Basic Project in the Trust Center settings.
- You must supply the line numbers of the lines in the entire module, not in the procedure. You'd need quite a bit more code to make it procedure specific.
- Clicking the comment/uncomment buttons is as easy IMO.
 
Pass the line numbers as parameters:
Code:
Sub CommentLines1to5(lStart as Long, lStop as Long)
   Dim n As Long
   With ThisWorkbook.VBProject.VBComponents("abc").CodeModule
       For n = lStart To lStop
            .ReplaceLine n, "'" & .Lines(n, 1)
       Next n
   End With
End Sub
Sub UncommentLines1to5(lStart as Long, lStop as Long)
   Dim n As Long
   With ThisWorkbook.VBProject.VBComponents("abc").CodeModule
       For n = lStart To lStop
            .ReplaceLine n, Mid$(.Lines(n, 1), 2)
       Next n
   End With
End Sub
 
Back
Top