私が次のものを持っているとしましょう:
Public Sub Information()
'TEST
End Sub
結果として「TEST」を取得する方法はありますか? 何とかVBAで?
例 - PHP では、コメントを取る良い方法があります。ここに何かアイデアはありますか?
編集: MZ-Tools のようなツールは、ドキュメントを生成するときにコメントを提供できるため、方法があるはずです。
VBA Extensibility ライブラリ (別名「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
モジュール内のコードを 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」に 1 つ追加します。