2015-10-02 50 views
0

我有很多具有#DIV/0的單元格!所以我需要把IFERROR函數。有沒有辦法將此公式應用於所有單元格,而不是將公式手動放入每個單元格中?如何將IFERROR應用於Excel中的所有單元格

我試過這個VBA代碼,但我正在尋找更簡單的東西。

Sub WrapIfError() 
Dim rng As Range 
Dim cell As Range 
Dim x As String 

    If Selection.Cells.Count = 1 Then 
    Set rng = Selection 
    If Not rng.HasFormula Then GoTo NoFormulas 
    Else 
     On Error GoTo NoFormulas 
     Set rng = Selection.SpecialCells(xlCellTypeFormulas) 
     On Error GoTo 0 
    End If 

    For Each cell In rng.Cells 
    x = cell.Formula 
    cell = "=IFERROR(" & Right(x, Len(x) - 1) & "," & Chr(34) & Chr(34) & ")" 
    Next cell 

Exit Sub 

'Error Handler 
NoFormulas: 
    MsgBox "There were no formulas found in your selection!" 

End Sub 

任何人都可以幫我嗎?

+0

這段代碼對我來說很不錯。有什麼問題? – Jeeped

+0

這對我來說不是問題,但我想使用簡單的東西,並教導不瞭解編程基礎知識的其他人使用它。 – user3619789

+0

我唯一可能想到的問題是'x = Mid(cell.Formula,2)'而不是'x = cell.Formula',以便從公式中刪除任何前導的'='。或者 - 更高級一點 - 你也可以使用:Iif(InStr(1,cell.Formula,「=」)> 0,Mid(selection.Formula,2),cell.Formula)'。 – Ralph

回答

1

也許其中一個版本會更容易教。

Sub apply_Error_Control() 
    Dim cel As Range 

    For Each cel In Selection 
     If cel.HasFormula Then 
      'option 1 
      cel.Formula = Replace(cel.Formula, "=", "=IFERROR(") & ", """")" 
      'option 2 
      'cel.Formula = "=IFERROR(" & Mid(cel.Formula, 2) & ", """")" 
     End If 
    Next cel 

End Sub 

我提供給應用IFERROR function作爲誤差控制「wapper」兩種方式。要使用第二個選項,請先註釋第一個選項,然後取消註釋第二個選項。

選擇一個或多個單元格,然後運行宏;通常通過Alt + F8然後從工作表運行

相關問題