可以说我有以下内容:
Public Sub Information()
'TEST
End Sub
有没有办法得到“测试”的结果?不知何故通过VBA?
例如 - 在 PHP 中有一个很好的方法来获取评论。这里有什么想法吗?
编辑:应该有办法,因为像 MZ-Tools 这样的工具能够在生成文档时提供注释。
您需要使用 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
一旦你有了一个模块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
因此,您需要迭代行,跟踪注释是否在下一行继续/从上一行继续,跳过字符串文字等。
玩得开心!
您可以使用 Microsoft Visual Basic for Applications Extensibility 在运行时检查代码:
'Requires reference to Microsoft Visual Basic for Applications Extensibility
'and trusted access to VBA project object model.
Public Sub Information()
'TEST
End Sub
Public Sub Example()
Dim module As CodeModule
Set module = Application.VBE.ActiveVBProject.VBComponents(Me.CodeName).CodeModule
Dim code As String
code = module.lines(module.ProcStartLine("Information", vbext_pk_Proc), _
module.ProcCountLines("Information", vbext_pk_Proc))
Dim lines() As String
lines = Split(code, vbCrLf)
Dim line As Variant
For Each line In lines
If Left$(Trim$(line), 1) = "'" Then
Debug.Print "Found comment: " & line
End If
Next
End Sub
请注意,上面的示例假定它在 Worksheet 或 Workbook 代码模块中运行(因此Me
在定位 时CodeModule
)。找到正确模块的最佳方法取决于您要在哪里找到该过程。
经过一些测试,我得到了这个解决方案:
只需将代码模块的名称传递给函数,它将打印所有注释行。内联注释不起作用(您必须更改条件)
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
您可以尝试在模块中逐行阅读代码。这只是返回第一条评论以进行进一步改进的想法:
Sub callIt()
Debug.Print GetComment("Module1")
End Sub
Function GetComment(moduleName As String)
Dim i As Integer
With ThisWorkbook.VBProject.VBComponents(moduleName).CodeModule
For i = 1 To .CountOfLines
If Left(Trim(.Lines(i, 1)), 1) = "'" Then
'here we have comments
'return the first one
GetComment = .Lines(i, 1)
Exit Function
End If
Next i
End With
End Function
重要的!在参考窗口中添加一个到“Microsoft Visual Basic for Applications Extensibility”。