2015-10-02 46 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然后从工作表运行

相关问题