编辑多个工作簿的公式以删除外部引用/更改对本地工作簿的引用

时间:2013-06-11 00:55:15

标签: excel-vba vba excel

我已将工作表复制到一批工作簿中(大约45个)。

此工作表包含公式和引用,即=Sheetname!A1=IF(Sheetname!A2=1, "this", "that").

但是,当复制工作表时,这些公式已成为

=[Original_Book.xlsm]Sheetname!$A$1

=IF([Original_Book.xlsm]Sheetname!A2=1, "this", "that").

我想要一种方法来删除所有“[Original_Book.xlsm]”引用,以便公式再次变为本地。

实际例子(以上仅供说明之用

=[Survey_Checker.xlsm]Output!D42

应该成为

=Output!D42

同样地:

=INDEX([Survey_Checker.xlsm]QR1!E3:[Survey_Checker.xlsm]QR1!E9,[Survey_Checker.xlsm]Output!$G$17,0)

应该成为

=INDEX(QR1!E3:QR1!E9,Output!$G$17,0)

等等。

实际上,如果有一个VBA方法从每个文件的单元格范围A1:PE5中的工作表(称为“DB输出”)中删除字符串“[Survey_Checker.xlsm]”的每个实例,相信可能有用?

编辑:A1和PE5之间的每一列都有一个需要删除的参考论坛。

1 个答案:

答案 0 :(得分:5)

这是原始宏的一个版本,添加了修复公式的代码。

Sub Example()
    Dim path As String
    Dim file As String
    Dim wkbk As Workbook
    Dim rCell As Range

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False


    path = "C:\Test\"
    file = Dir(path)

    Do While Not file = ""
        Workbooks.Open (path & file)
        Set wkbk = ActiveWorkbook
        Sheets.Add After:=Sheets(Sheets.Count)
        On Error GoTo Sheet_Exists
        ActiveSheet.Name = "DB Output"
        On Error GoTo 0
        ThisWorkbook.Sheets("DB Output").Range("A1:PE5").Copy Destination:=wkbk.Sheets("DB Output").Range("A1")

        For Each rCell In wkbk.Sheets("DB Output").UsedRange
            If InStr(rCell.Formula, ThisWorkbook.Name) > 0 Then
                rCell.Replace What:="[*]", Replacement:=""
            End If
        Next

        wkbk.Save
        wkbk.Close
        file = Dir
    Loop

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Exit Sub

Sheet_Exists:
    Sheets("DB Output").Delete
    Resume
End Sub

这是一个只会从公式中删除工作簿引用的宏

Sub Example()
    Dim path As String
    Dim file As String
    Dim rCell As Range

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False


    path = "C:\Test\"
    file = Dir(path)

    Do While Not file = ""
        Workbooks.Open (path & file)

        Sheets("DB Output").Select

        For Each rCell In ActiveWorkbook.Sheets("DB Output").UsedRange
            rCell.Replace What:="[*]", Replacement:=""
        Next

        ActiveWorkbook.Save
        ActiveWorkbook.Close
        file = Dir
    Loop

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
End Sub