views:

2214

answers:

1

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\
Microsoft\Excel\XLSTART\pcs.xls'!MyMacroFunction()

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
  Next
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.

A: 

Try the following:

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

I called this with:

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

This was hacked from:

Macros to Delete Formula Links

Bravax