VBA Wrap IFERROR修改

时间:2016-12-28 19:48:56

标签: excel vba excel-vba

我对VBA非常生疏,因此我希望对于那些精通VBA的人来说,这将是一个简单的修改。我想修改下面的公式,以便让我的IFERROR函数在发生错误时返回0,“”或n / a。目前我在网上找到的代码是完美的,但不会返回n / a。如果有人知道如何快速添加一个代码块,允许第三个选项循环通过将欣赏它。代码来自www.TheSpreadsheetGuru.com

Sub WrapIfError_v2()

'PURPOSE: Add an IFERROR() Function around all the selected cells' formulas. _
          Also handles if IFERROR is already wrapped around formula.
'SOURCE: www.TheSpreadsheetGuru.com

Dim rng As Range
Dim cell As Range
Dim AlreadyIFERROR As Boolean
Dim RemoveIFERROR As Boolean
Dim TestEnd1 As String
Dim TestEnd2 As String
Dim TestEnd3 As String
Dim TestStart As String
Dim MyFormula As String
Dim x As String

'Determine if a single cell or range is selected
  If Selection.Cells.Count = 1 Then
    Set rng = Selection
    If Not rng.HasFormula Then GoTo NoFormulas
  Else
    'Get Range of Cells that Only Contain Formulas
      On Error GoTo NoFormulas
        Set rng = Selection.SpecialCells(xlCellTypeFormulas)
      On Error GoTo 0
  End If

'Get formula from First cell in Selected Range
  MyFormula = rng(1, 1).Formula

'Create Test Strings To Determine if IFERROR formula has already been added
  TestEnd1 = Chr(34) & Chr(34) & ")"
  TestEnd2 = ",0)"
  TestStart = Left(MyFormula, 9)

'Determine How we want to modify formula
  If Right(MyFormula, 3) = TestEnd1 And TestStart = "=IFERROR(" Then
    Beg_String = ""
    End_String = "0)" '=IFERROR([formula],0)
    AlreadyIFERROR = True
  ElseIf Right(MyFormula, 3) = ",0)" And TestStart = "=IFERROR(" Then
    RemoveIFERROR = True
  Else
    Beg_String = "=IFERROR("
    End_String = "," & Chr(34) & Chr(34) & ")" '=IFERROR([formula],"")
    AlreadyIFERROR = False
  End If

'Loop Through Each Cell in Range and modify formula
  For Each cell In rng.Cells
    x = cell.Formula

    If RemoveIFERROR = True Then
      cell = "=" & Mid(x, 10, Len(x) - 12)
    ElseIf AlreadyIFERROR = False Then
      cell = Beg_String & Right(x, Len(x) - 1) & End_String
    Else
      cell = Left(x, Len(x) - 3) & End_String
    End If

  Next cell

Exit Sub

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

End Sub

1 个答案:

答案 0 :(得分:0)

答案在于在以下代码块中更改End_String的值:

'Determine How we want to modify formula
  If Right(MyFormula, 3) = TestEnd1 And TestStart = "=IFERROR(" Then
    Beg_String = ""
    End_String = "0)" '=IFERROR([formula],0)
    AlreadyIFERROR = True
  ElseIf Right(MyFormula, 3) = ",0)" And TestStart = "=IFERROR(" Then
    RemoveIFERROR = True
  Else
    Beg_String = "=IFERROR("
    End_String = "," & Chr(34) & Chr(34) & ")" '=IFERROR([formula],"")
    AlreadyIFERROR = False
  End If

例如,而不是

& Chr(34) & Chr(34) & ")"

你可以替代:

& "NA())"

这接近你想要的吗?