我可以在VBA代码中获取评论文本吗

Vit*_*ata 4 excel vba excel-vba vbe

可以说我有以下几点:

Public Sub Information()
    'TEST
End Sub
Run Code Online (Sandbox Code Playgroud)

有没有办法获得“测试”结果?通过VBA以某种方式?

例如-在PHP中,有一种接受注释的好方法。这里有什么想法吗?

编辑:应该有一种方法,因为MZ-Tools之类的工具能够在生成文档时提供注释。

Mat*_*don 5

您需要使用VBA可扩展性库(也称为“ VBIDE API”)自己解析代码。添加对Microsoft Visual Basic for Applications Extentibility 5.3类型库的引用,然后可以访问诸如CodePane和的类型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
Run Code Online (Sandbox Code Playgroud)

一旦有了模块的contents,就需要实现逻辑来查找注释...这可能很棘手-以下是一些示例代码:

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
Run Code Online (Sandbox Code Playgroud)

因此,您需要迭代各行,跟踪注释是否在下一行继续/从上一行继续,跳过字符串文字,等等。

玩得开心!