假设我有以下内容:
Public Sub Information()
'TEST
End Sub
结果是否有办法获得“TEST”? 不知何故通过VBA?
E.g。 - 在PHP中有一个很好的方式来评论。这里有什么想法吗?
编辑: 应该有办法,因为像MZ-Tools这样的工具能够在生成文档时提供注释。
答案 0 :(得分:4)
您可以使用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
请注意,上面的示例假设它在Workheet或Workbook代码模块中运行(因此在找到Me
时CodeModule
)。找到正确模块的最佳方法取决于您希望找到该过程的位置。
答案 1 :(得分:4)
您需要使用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
所以你需要迭代这些行,跟踪评论是否在下一行继续/从前一行继续,跳过字符串文字等等。
玩得开心!
答案 2 :(得分:3)
经过一些测试,我得到了这个解决方案:
只需将代码模块的名称传递给函数,它将打印所有注释行。内联注释不起作用(您必须更改条件)
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
答案 3 :(得分:1)
您可以尝试逐行阅读模块中的代码。以下是返回第一条评论以进一步改进的想法:
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'。
”