且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从VBA代码检查Excel单元格中的#N / A

更新时间:2023-02-13 16:30:46

首先检查错误(N / A值),然后尝试与cvErr()进行比较。你正在比较两个不同的东西,一个价值和一个错误。这可能工作,但不总是。简单地将表达式转换为错误可能会导致类似的问题,因为它不是真正的错误,只是取决于表达式的错误的值。

 code>如果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


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

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