vba - 如何在 MS Office 2013 中自动查找/替换 VBA 模块中的代码?

标签 vba excel ms-office vbe

我有大量包含需要更新的 VBA 代码的 Excel 模板。代码模块对象的 Find 方法仅返回 true/false,而不返回找到的字符串的位置。

有什么方法可以自动执行查找和替换过程吗?

最佳答案

将此代码添加到新的启用宏的工作簿中。设置 FIND_WHAT 和 REPLACE_WITH 常量,打开其他工作簿并运行代码。

原始代码来自Charles Pearson's site

警告:仅完成了基本测试!

Option Explicit

Sub ReplaceTextInCodeModules()

' Must add a reference to "Microsoft Visual Basic For Applications Extensibility 5.3"
' Also must set "Trust access to the VBA project object model"
' See the url below for more info on these.
' Based on code found at:
' Source: www.cpearson.com/excel/vbe.aspx Copyright 2013, Charles H. Pearson

Dim theWorkbook As Workbook
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule
Dim numLines As Long ' end line
Dim lineNum As Long
Dim thisLine As String
Dim message As String
Dim numFound As Long

Const FIND_WHAT As String = "findthis"
Const REPLACE_WITH As String = "replaced"

    numFound = 0

    For Each theWorkbook In Application.Workbooks
        If theWorkbook.Name <> ThisWorkbook.Name Then
            If theWorkbook.HasVBProject Then
                Set VBProj = theWorkbook.VBProject
                For Each VBComp In VBProj.VBComponents
                    'Set VBComp = VBProj.VBComponents("Module1")
                    Set CodeMod = VBComp.CodeModule

                    With CodeMod
                        numLines = .CountOfLines
                        For lineNum = 1 To numLines
                            thisLine = .Lines(lineNum, 1)
                            If InStr(1, thisLine, FIND_WHAT, vbTextCompare) > 0 Then
                                message = message & theWorkbook.Name & " | " & VBComp.Name & " | Line #" & lineNum & vbNewLine
                                .ReplaceLine lineNum, Replace(thisLine, FIND_WHAT, REPLACE_WITH, , , vbTextCompare)
                                numFound = numFound + 1
                            End If
                        Next lineNum
                    End With
                Next VBComp
            End If
        End If
    Next theWorkbook

    Debug.Print "Found: " & numFound
    If message <> "" Then
        Debug.Print message
    End If

End Sub

关于vba - 如何在 MS Office 2013 中自动查找/替换 VBA 模块中的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30848609/

相关文章:

layout - 维西奥 2010 : Prevent Co-Linear Connector Routes

如果行的一个单元格以特定字符串开头,VBA Excel 删除该行

vba - Excel VBA - 使用变量时 MkDir 返回 "Path not Found"

sql-server - 将存储过程返回值分配给 VBA 变量

java - 如何使用 HSSF(Apache POI)在现有 excel 的两行之间插入一行

excel - VBA 的 Sumif 始终使用前一列的前一个单元格作为参数,直到列结束

excel - 如何在 VBA Excel 中正确使用通配符字符列表

java - 如何正确格式化日期单元格并使用 Apache POI 3.7 填充内容

excel - 如何在特定工作表中运行宏,但根据从另一个 Excel 文件/工作表维护的值控制开始?

java - 如何在 Java Applet 中显示 PPT 文件?