Scan documents for macro and replace macro text?

I am presented with a puzzle. Where I work, there are a huge number of Word templates in which everything contains an autonew event descriptor that contains some errors. And this error lies in all templates. And I was wondering if there could be a way to scan the directory for templates that contains this macro and change the macro code a bit?

Is it possible?

+3
source share
1 answer

Yes you can do it. You can access the VBA project of any document using:

Application.VBE.ActiveVBProject.VBComponents

Your project should have a link to Microsoft Visual Basic for application extensibility.

, " Visual Basic Project" Word,

- > - > ( "" )

VBComponents , , "", . Google, , /.

: , . VBComponents , , / .

Public Sub ReplaceInProject(ByVal oDocument As Document, ByVal strMethodName As String, ByVal strFindText As String, ByVal strReplaceWithText As String)

    ' For each module (of any type - could use oVbComponent.Type to restrict
    ' this to certain types of module)

    Dim oVbComponent As VBComponent
    For Each oVbComponent In oDocument.VBProject.VBComponents

        Dim oCodeModule As CodeModule
        Set oCodeModule = oVbComponent.CodeModule

        ' See if we can find the method in this module

        Dim ixStartLine As Long
        ixStartLine = FindMethodStartLine(oCodeModule, strMethodName)

        If ixStartLine > 0 Then

            ' Get all the text of the method

            Dim numLines As Long
            numLines = oCodeModule.ProcCountLines(strMethodName, vbext_pk_Proc)

            Dim strLines As String
            strLines = oCodeModule.Lines(ixStartLine, numLines)

            ' Do the find/replace

            strLines = Replace(strLines, strFindText, strReplaceWithText)

            ' Replace the method text.

            oCodeModule.DeleteLines ixStartLine, numLines

            oCodeModule.InsertLines ixStartLine, strLines

        End If

    Next oVbComponent

End Sub

Private Function FindMethodStartLine(ByVal oCodeModule As CodeModule, ByVal strMethodName As String) As Long

    FindMethodStartLine = 0

    ' ProcStartLine will raise an error if the method is not found;
    ' we'll just ignore the error and return -1

    On Error Resume Next
    FindMethodStartLine = oCodeModule.ProcStartLine(strMethodName, vbext_pk_Proc)

End Function

, Sub Function, Get/Set/Let, vbext_pk_Proc. PITA, . , API CodeModule , . , VbComponent Find (, , , ), True False (!). , !

API , .

+8

Source: https://habr.com/ru/post/1722988/


All Articles