【问题标题】:How can I have a VBA macro perform a Search/Replace in formulas across an entire workbook?如何让 VBA 宏在整个工作簿的公式中执行搜索/替换?
【发布时间】:2010-10-06 18:41:10
【问题描述】:

我将 Excel 工作簿分发给多个用户,他们应该在他们的 XLSTART 文件夹中预装了一个特定的宏文件。

如果他们没有正确安装宏,并且他们将工作簿发回给我,则任何依赖于它的公式都包含宏的完整路径,例如:

'C:\Documents and Settings\richard.tallent\Application Data\
Microsoft\Excel\XLSTART\pcs.xls'!MyMacroFunction()

我想创建一个快速宏,可用于从工作簿中的每个公式中删除不正确的路径

我已经使用 GetSpecialFolder(一个工作正常的外部函数)成功检索了特殊文件夹,但下面显示的 Replace 调用本身会引发“应用程序定义或对象定义错误”。

Public Sub FixBrokenMacroFormulas()
  Dim badpath As String
  badpath = "'" & GetSpecialFolder(AppDataFolder) & "\Microsoft\Excel\XLSTART\mymacro.xls'!"
  Dim Sheet As Worksheet
  For Each Sheet In ActiveWorkbook.Sheets
      Call Sheet.Activate
      Call Sheet.Select(True)
      Call Selection.Replace(What:=badpath, Replacement:="", LookIn:=xlFormulas)
      ''//LookAt:=xlPart, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
  Next
End Sub

自动搜索和替换并不是我的强项,我做错了什么?

我已经注释掉了一些看起来并不重要的参数。

【问题讨论】:

    标签: excel replace vba


    【解决方案1】:

    不需要使用这样的函数,您可以使用以下语句:

     'Replace with a reference to other workbook
      xlBook.ChangeLink Name:= _
         "C:\LISTADOS\reporte_gestion_sucursales\modelo_vaciado\modelo_reporte.xlsx", _
         NewName:=fileIn2, Type:=xlExcelLinks
    

    【讨论】:

      【解决方案2】:

      尝试以下方法:

      Sub FormulaFindAndReplace(phrase As String)
        For Each Sheet_Select In ActiveWorkbook.Worksheets
          Sheet_Select.Activate
          Set Found_Link = Cells.Find(what:=phrase, After:=ActiveCell, _
              LookIn:=xlFormulas, lookat:=xlPart, searchorder:=xlByRows, _
              searchdirection:=xlNext, MatchCase:=False)
          While UCase(TypeName(Found_Link)) <> UCase("Nothing")
             Found_Link.Activate
             Found_Link.Formula = Replace(Found_Link.Formula, phrase, "")
             Set Found_Link = Cells.FindNext(After:=ActiveCell)
          Wend
        Next Sheet_Select
      End Sub
      

      我这样称呼它:

      FormulaFindAndReplace "'" & GetSpecialFolder(AppDataFolder) & "\Microsoft\Excel\XLSTART\mymacro.xls'!"  
      

      这是被黑客入侵的:

      Macros to Delete Formula Links

      【讨论】:

        猜你喜欢
        • 2021-04-03
        • 2018-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-14
        相关资源
        最近更新 更多