Home » excel » excel vba – How can I have a VBA macro perform a Search/Replace in formulas across an entire workbook?

excel vba – How can I have a VBA macro perform a Search/Replace in formulas across an entire workbook?

Posted by: admin May 14, 2020 Leave a comment


I distribute an Excel workbook to a number of users, and they are supposed to have a particular macro file pre-installed in their XLSTART folder.

If they don’t have the macro installed correctly, and they send the workbook back to me, any formulas depending on it include the full path of the macro, e.g.:

'C:\Documents and Settings\richard.tallent\Application Data\

I want to create a quick macro I can use to remove the improper path from every formula in the workbook.

I’ve successfully retrieved the special folder using GetSpecialFolder (an external function that is working just fine), but the Replace call itself shown below throws an “Application-defined or object-defined error”.

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
End Sub

Automating search and replace isn’t exactly my forte, what am I doing wrong?

I’ve already commented out some of the parameters that don’t seem essential.

How to&Answers:

Try the following:

Sub FormulaFindAndReplace(phrase As String)
  For Each Sheet_Select In ActiveWorkbook.Worksheets
    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.Formula = Replace(Found_Link.Formula, phrase, "")
       Set Found_Link = Cells.FindNext(After:=ActiveCell)
  Next Sheet_Select
End Sub

I called this with:

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

This was hacked from:

Macros to Delete Formula Links


There is no need to use such a function, you could instead just use the following statement:

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