gpt4 book ai didi

vba - 单独导出VBA程序(子/函数)

转载 作者:行者123 更新时间:2023-12-02 12:09:10 27 4
gpt4 key购买 nike

在该项目中,我正在处理的所有代码都位于模块中,每个模块都有不同数量的过程。我正在尝试将 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

最佳答案

我认为问题的关键是检查该行包含术语“function”是否还包含函数名称后面的左括号。例如:私有(private)函数 foo(。因此,您希望计算 1 个空格字符,并且在下一个空格或逗号字符之前至少有 1 个左括号。

关于vba - 单独导出VBA程序(子/函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50707967/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com