gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:03:10 25 4
gpt4 key购买 nike

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

有没有办法自动化查找和替换过程?

最佳答案

将此代码添加到启用宏的新工作簿。设置FIND_WHATREPLACE_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/

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