您无法使用正则表达式 - 句点在 VBA 代码中找到所有注释(更不用说字符串文字)。相信我,我在研究智能压头模块时尝试过橡皮鸭(如果这还不够明确 - 完全披露,我是贡献者)。您需要实际解析代码。您将遇到的第一个问题是行延续:
'Comment with a line _
continuation
Debug.Print 'End of line comment _
with line continuation.
Debug.Print 'Multiple line continuation operators _ _
still work.
Debug.Print 'This is actually *not* a line continuation_
Debug.Print 42
这使得识别字符串文字变得困难,特别是您正在使用逐行处理:
Debug.Print 42 'The next line... _
"...is not a string literal"
你还必须处理旧的Rem
注释语法...
Rem old school comment
...也支持行延续:
Rem old school comment with line _
continuation.
您可能会想“这不会那么糟糕,雷姆必须开始排队”。如果是,那么您忘记了语句分隔符(:
)...
Debug.Print 42: Rem statement separator comment.
...或者它的邪恶孪生语句分隔符与行延续相结合:
Debug.Print 42: Rem this can be _
continued too.
您通过整理字符串文字和注释解决了一些问题,如下所示......
Debug.Print "Unmatched double quotes." 'Comment"
Debug.Print "Interleaved single 'n double quotes." 'Comment"
...但是像这个野兽这样的括号标识符呢(由@ThunderFrame 提供)?
'No comments or strings in the line below.
Debug.Print [Evil:""Comment"'here]
请注意,语法高亮SO使用甚至没有捕捉到所有这些奇怪的极端情况。