20

I'm iterating through a range of cells which hold numbers with 2 decimal places. I need to check if the cell holds '#N/A', and if it does, I need to skip it. The problem is, when a cell holds a valid number, my if condition below throws a 'Type mismatch error'. How can I avoid this?

If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
'do something
End If
2
  • Sorry, asked the question hastily. Casting LHS of expression as CVErr fixes it. Commented Feb 28, 2011 at 14:44
  • You can also use IsError(rg) if you're not concerned about the specific type of error. Commented Jul 16, 2014 at 18:03

1 Answer 1

27

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If
Sign up to request clarification or add additional context in comments.

5 Comments

There is also Application.IsNA, which you would use like: 'If Application.IsNA(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then'
Could not find the Application.IsNA() in excel 2010 @jtolle
@pablete: It's there! You can use either Application.IsNA() (which will not show up in VBA's little autocomplete suggestion), or Application.WorksheetFunction.IsNA(), which will. For example, try this in the Immediate window: ?application.isna([na()]). You should get back True.
Ahh, ok, now it works (does not show on the auto complete feature), thanks a lot.
IMO, as the N/A error is part of all errors found by IsError, the first command suffice the asked need. Only, it shall be negated to skip erroneous rows - If Not IsError(...) Then 'do something.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.