2017-02-13 121 views
-1

我有一系列的函數都是由各種數據集和數據透視表構建而成的。在某些數據操作過程中,其中一個表被刪除並重新創建。這打破了依賴於表名的幾個公式。Excel VBA:#REF!查找並替換

我正在尋找一種方法來搜索和替換所有公式,使用VBA,(請記住它們都略有不同),以取代#REF!與術語「DATASETNEW」。

一個這樣的公式的一個例子是:

=IF(ISNA(VLOOKUP($A2,#REF!,4,FALSE)="12000"),"No Stock",VLOOKUP($A2,#REF!,5,FALSE)) 
+0

如果必須在VBA中:循環遍歷所有工作表的所有UsedCells的公式,無論是在內存中(快很多)還是範圍,然後相應地更改公式。 – PatricK

+0

...任何想法我會怎麼做?我可以用公式遍歷所有單元格並替換整個公式,但我不知道如何替換#REF!文本? –

回答

0

查找和替換(按Ctrl + H)將式內更新它們。

+0

是的。我真的想以編程方式來做。 –

0

你可以試試這個:

Option Explicit 

Sub ChangeFormulas() 
    Const LOOK_FOR As String = "#REF!" 
    Const REPLACE_WITH As String = "DATASETNEW" 
    Dim oWS As Worksheet, lCalcMode As Long 
    Dim aFormulas As Variant, r As Long, c As Long, bHasLookFor As Boolean 

    lCalcMode = Application.Calculation 
    Application.Calculation = xlCalculationManual 
    Debug.Print "WORKSHEET", "ROW", "COLUMN", """" & LOOK_FOR & """?", "FORMULA" 
    For Each oWS In ThisWorkbook.Worksheets 
     aFormulas = oWS.UsedRange.Formula 
     Select Case oWS.UsedRange.Cells.Count 
      Case Is > 1 
       For r = LBound(aFormulas, 1) To UBound(aFormulas, 1) 
        For c = LBound(aFormulas, 2) To UBound(aFormulas, 2) 
         bHasLookFor = (InStr(1, aFormulas(r, c), LOOK_FOR, vbTextCompare) > 0) 
         If bHasLookFor Then 
          Debug.Print oWS.Name, r, c, bHasLookFor, aFormulas(r, c) 
          oWS.UsedRange.Cells(r, c).Formula = Replace(aFormulas(r, c), LOOK_FOR, REPLACE_WITH) 
         End If 
        Next c 
       Next r 
      Case 1 
       bHasLookFor = (InStr(1, aFormulas, LOOK_FOR, vbTextCompare) > 0) 
       If bHasLookFor Then 
        Debug.Print oWS.Name, 1, 1, bHasLookFor, aFormulas 
        oWS.UsedRange.Cells(1, 1).Formula = Replace(aFormulas, LOOK_FOR, REPLACE_WITH) 
       End If 
     End Select 
    Next oWS 
    Application.Calculation = lCalcMode 
End Sub 

通過在工作簿中的所有工作表這將循環,尋找,必要時更換這些字符串。它顯示立即窗口上的進度。