0

I am trying to add code that will search for the string #DIV/0! in a range of cells (EF:W10) and if found, will replace that cell with NA. Below is what I have, but it is not quite working. What am I missing?

Dim rngDiv As Range
For Each rngDiv In Range("E4:W10")
    If InStr(rngDiv.Value, "#DIV/0!") > 0 Then
        rngDiv.Value = "NA"
    End If
Next rngDiv
4
  • 1
    Instead of using a sledgehammer to kill a fly, why don't you change the formula in those cells to =IFERROR([current formula],"NA") ? Commented Jan 4, 2017 at 15:13
  • agree with @MacroMan! Commented Jan 4, 2017 at 15:15
  • No can do. The entire code needs to be in the script so that it can be run on a blank new excel sheet. Commented Jan 4, 2017 at 15:18
  • But then the script must be adding the formula to your cells at some point. Make the script add macromans formula instead of the current one. Commented Jan 4, 2017 at 15:24

2 Answers 2

3

If you really need VBA to do this then you can use the IsError() function

Dim rngDiv As Range
For Each rngDiv In Range("E4:W10")
    If IsError(rngDiv) Then
        rngDiv.Value = "NA"
    End If
Next

However it's best to catch your errors in the actual formula rather than afterwards with VBA.


Note: The above will catch all errors - if you just want the #DIV/0! error then you need to test for the .Text property instead of the .Value property:

Dim rngDiv As Range
For Each rngDiv In Range("E4:W10")
    If rngDiv.Text = "#DIV/0!" Then
        rngDiv.Value = "NA"
    End If
Next rngDiv
Sign up to request clarification or add additional context in comments.

1 Comment

Yes this is what I was looking for. Thank you
0

How about:

Sub marine()
    Dim rngDiv As Range
    For Each rngDiv In Range("E4:W10")
        If rngDiv.Text = "#DIV/0!" Then
            rngDiv.Value = "NA"
        End If
    Next rngDiv
End Sub

1 Comment

Strangely enough - I was actually going to link to an old post of yours...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.