【发布时间】:2018-06-05 19:55:12
【问题描述】:
在我正在处理的项目中,我的所有代码都位于模块中,每个模块都有不同数量的过程。我正在尝试将 VBA 代码过程一一导出到以其各自模块命名的文件夹中。我已经有了导出整个模块的代码,但我喜欢这个挑战,而且以这种方式跟踪更改更有趣!
下面的导出代码适用于除自身之外的每个模块,因为我检查函数/子的开始和结束的方式。这是一个循环问题,真的,因为它认为检查中的短语是新子的开始!
如果有人有一个更有创意的解决方案来标记可以在这里工作的函数或子的开始和结束,或者有办法调整我的,我将不胜感激!
Sub ExportVBCode2()
'NOTE: Globals will be included with the first procedure exported, not necessarily the procedure(s) they're used in
Dim directory As String
directory = "C:\Users\Public\Documents\VBA Exports" & "\"
Dim fso As Object
Set fso = CreateObject("scripting.filesystemobject")
' If fso.FolderExists(Left(directory, Len(directory) - 1)) Then
' fso.deletefolder Left(directory, Len(directory) - 1)
' End If
If Len(Dir(directory, vbDirectory)) = 0 Then
MkDir directory
End If
Dim VBComponent As Object
Dim Fileout As Object
Dim i As Long
Dim currLine As String
Dim currLineLower As String
Dim functionString As String
Dim functionName As String
Dim funcOrSub As String
For Each VBComponent In ThisWorkbook.VBProject.VBComponents
If VBComponent.Type = 1 Then 'Component Type 1 is "Module"
If Len(Dir(directory & "\" & VBComponent.Name & "\", vbDirectory)) = 0 Then
MkDir directory & VBComponent.Name
End If
For i = 1 To VBComponent.CodeModule.CountOfLines
currLine = RTrim$(VBComponent.CodeModule.Lines(i, 1))
currLineLower = LCase$(currLine)
'TODO need a more clever solution for the if check below, because it catches ITSELF. Maybe regex ?
If (InStr(currLineLower, "function ") > 0 Or InStr(currLineLower, "sub ") > 0) And InStr(currLineLower, "(") > 0 And InStr(currLineLower, ")") > 0 Then
'this is the start of a new function
Select Case InStr(currLineLower, "function ")
Case Is > 0
funcOrSub = "function"
Case Else
funcOrSub = "sub"
End Select
functionName = Mid(currLine, InStr(currLineLower, funcOrSub) + Len(funcOrSub & " "), InStr(currLine, "(") - InStr(currLineLower, funcOrSub) - Len(funcOrSub & " "))
End If
functionString = functionString & currLine & vbCrLf
If Trim$(currLineLower) = "end sub" Or Trim$(currLineLower) = "end function" Then
'this is the end of a function
Set Fileout = fso.CreateTextFile(directory & "\" & VBComponent.Name & "\" & functionName & ".txt", True, True)
Fileout.Write functionString
Fileout.Close
functionString = ""
functionName = ""
End If
Next i
End If
Next VBComponent
End Sub
【问题讨论】:
-
额头拍打 是的,那真的很容易,不是吗?回到绘图板似乎:)
-
@MathieuGuindon 顺便说一句,我真的很喜欢 Rubberduck - 希望我能把它放在我工作的机器上!
-
添加要查找的唯一注释字符串。如果您在一行中执行此操作,您可以检查
'是否是修剪后的字符串中的第一个字符。也有一个关闭的唯一注释行(可能匹配),只是让它忽略这些注释行之间的代码行。 -
@Mistella 是的,这是一种我绝对可以成功的创造性方法
-
@T.M.大声笑,当我今天回头看那个答案时,我只是在想。谢谢