且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在运行任何过程之前和之后自动执行代码

更新时间:2021-09-26 23:23:49

使用1个程序的1个模块,但可以迭代所有模块的所有过程并使用相同的逻辑。它使用Jon Crowell的程序。

This example only work with 1 procedure of 1 module but you can iterate all the procedures of all modules and use the same logic. It uses the procedures from Jon Crowell.

Private Sub SwitchHeaderFooter()

    Dim lineNr As Long
    Dim procName As String
    Dim strHeader As String
    Dim strFooter As String

    procName = "TestProc"
    strHeader = "Call GetReadyToProcess"
    strFooter = "Call ReturnSettingsToWhatTheyWere"

    Dim vbComp As VBIDE.VBComponent
    Dim vbModule As VBIDE.CodeModule
    Set vbComp = ThisWorkbook.VBProject.VBComponents("ModuleTest")
    Set vbModule = vbComp.CodeModule

    lineNr = vbModule.ProcBodyLine(procName, vbext_pk_Proc)
    If (vbModule.Lines(lineNr + 1, 1) = strHeader) Then
        vbModule.DeleteLines lineNr + 1, 1
    Else
        vbModule.InsertLines lineNr + 1, strHeader
    End If

    lineNr = vbModule.ProcCountLines(procName, vbext_pk_Proc)
    If (vbModule.Lines(lineNr - 1, 1) = strFooter) Then
        vbModule.DeleteLines lineNr - 1, 1
    Else
        vbModule.InsertLines lineNr, strFooter
    End If

End Sub

在ModuleTest中,在第一次执行之前:

In your ModuleTest, before the 1st execution:

Sub TestProc()
    MsgBox "This is a test procedure!"
End Sub

第一次执行后:

Sub TestProc()
Call GetReadyToProcess
    MsgBox "This is a test procedure!"
Call ReturnSettingsToWhatTheyWere
End Sub

最后,第二次执行后: p>

Finally, after the 2nd execution:

Sub TestProc()
    MsgBox "This is a test procedure!"
End Sub