C# vba-扫描文档中的宏并替换宏文本?

C# vba-扫描文档中的宏并替换宏文本?,c#,vb.net,vba,C#,Vb.net,Vba,我遇到了一个难题。我工作的地方有大量的Word模板,它们都包含一个包含一些错误的autonew eventhandle。这个错误存在于所有模板中。我想知道是否有一种方法可以扫描包含该宏的模板目录,并稍微更改宏代码 这可能吗?是的,你可以做到。您可以使用以下方式访问任何文档的VBA项目: Application.VBE.ActiveVBProject.VBComponents 您的项目必须引用“Microsoft Visual Basic for Applications Extensibili

我遇到了一个难题。我工作的地方有大量的Word模板,它们都包含一个包含一些错误的autonew eventhandle。这个错误存在于所有模板中。我想知道是否有一种方法可以扫描包含该宏的模板目录,并稍微更改宏代码


这可能吗?

是的,你可以做到。您可以使用以下方式访问任何文档的VBA项目:

Application.VBE.ActiveVBProject.VBComponents
您的项目必须引用“Microsoft Visual Basic for Applications Extensibility”

要运行代码,必须使用启用Word中的“信任访问Visual Basic项目”选项

工具->宏->安全性(受信任) “发布者”选项卡)

VBComponents
集合包含项目包含的所有标准模块、类模块、表单和“文档”模块。如果你用谷歌搜索它,你会发现很多关于如何访问/修改它们的帮助

编辑:好的,更多细节。此方法将搜索文档的所有
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\u pk\u Proc
。这是一个皮塔,你需要明确的关于这一点。坦率地说,
CodeModule
组件的整个API似乎都是为了挫败设计的。例如,虽然
VbComponent
对象有一个
Find
方法(您认为这是查找所查找文本的方便方法),但它实际上返回
True
False
(!)。有用,我不认为

此API的设计者在执行此操作时一定有一个非常糟糕的后遗症。

谢谢:)因此我将此添加到我的项目中并导入了Microsoft.Vbe.Interop,但是您知道如何将Word文档中的宏加载到Visual Studio项目中的文本框中吗?然后编辑文本,然后再次保存?还是用宏生成Word文件,然后将宏从该文档复制到下一个文档中更好?