[英]Excel VBA: #REF! Find & Replace
我有一系列函數,它們都是基於各種數據集和數據透視表構建的。 在某些數據操作期間,其中一個表被刪除並重新創建。 這打破了幾個依賴於該表名的公式。
我正在尋找一種在所有公式中搜索和替換的方法,使用 VBA(請記住,它們都略有不同)來替換 #REF! 用術語“DATASETNEW”。
一個這樣的公式的例子是:
=IF(ISNA(VLOOKUP($A2,#REF!,4,FALSE)="12000"),"No Stock",VLOOKUP($A2,#REF!,5,FALSE))
查找和替換 (Ctrl+H) 將在公式中更新它們。
你可以試試這個:
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
這將遍歷工作簿中的所有工作表,如果需要,查找並替換這些字符串。 它在立即窗口中顯示進度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.