Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get the text of the comments in the VBA code

Tags:

excel

vba

vbe

Lets say I have the following:

Public Sub Information()
    'TEST
End Sub

Is there a way to get "TEST" as a result? Somehow through VBA?

E.g. - In PHP there is a good way to take the comments. Any ideas here?

Edit: There should be a way, because tools like MZ-Tools are able to provide the comments when they generate the documentation.

like image 318
Vityata Avatar asked Dec 07 '22 20:12

Vityata


2 Answers

You need to parse the code yourself, using the VBA Extensibility library (aka "VBIDE API"). Add a reference to the Microsoft Visual Basic for Applications Extentibility 5.3 type library, and then you can access types such as CodePane and VBComponent:

Sub FindComments()

    Dim component As VBComponent
    For Each component In Application.VBE.ActiveVBProject.VBComponents
        Dim contents As String
        contents = component.CodeModule.Lines(1, component.CodeModule.CountOfLines)
        '"contents" now contains a string with the entire module's code.

        Debug.Print ParseComments(contents) 'todo

    Next

End Sub

Once you have a module's contents, you need to implement logic to find comments... and that can be tricky - here's some sample code to play with:

Sub Test()
    Dim foo 'this is comment 1

    'this _
       is _
            comment 2

    Debug.Print "This 'is not a comment'!"

    '..and here's comment 3

    REM oh and guess what, a REM instruction is also a comment!
    Debug.Print foo : REM can show up at the end of a line, given an instruction separator
End Sub

So you need to iterate the lines, track whether the comment is continuing on the next line / continued from the previous line, skip string literals, etc.

Have fun!

like image 77
Mathieu Guindon Avatar answered Dec 10 '22 12:12

Mathieu Guindon


After some tests, I got to this solution:

simply pass the name of the code-module to the function and it will print all comment lines. Inline comments won't work(you have to change the condition)

Function findComments(moduleName As String)

Dim varLines() As String
Dim tmp As Variant

With ThisWorkbook.VBProject.VBComponents(moduleName).CodeModule

    'split the lines of code into string array
    varLines = Split(.lines(1, .CountOfLines), vbCrLf)
End With

'loop through lines in code
For Each tmp In varLines

    'if line starts with '
    If Trim(tmp) Like "'*" Then

        'print comment line
        Debug.Print Trim(tmp)
    End If
Next tmp
End Function
like image 29
gizlmo Avatar answered Dec 10 '22 13:12

gizlmo