如何确定单元格中的错误值,类似于VBA.IsError

时间:2015-10-05 16:46:06

标签: vb.net excel

我有一个Excel电子表格。我试图测试公式是否会导致错误。 VBA有VBA.IsError,我正在寻找VB.net中的等价物。

    Dim CurrCell As Excel.Range = ws.Range("B10")
    CurrCell.Formula = "=DATEVALUE(-1)" 'results in #VALUE! error
    CurrCell.Select()

    'doesn't detect error
    If Microsoft.VisualBasic.IsError(CurrCell.Value) Then
        Debug.Print("error")
    Else
        Debug.Print("not error")
    End If

    'doesn't detect error; shows as VariantType.Integer
    Debug.Print(VarType(CurrCell.Value))
    If VarType(CurrCell.Value) = VariantType.Error Then
        Debug.Print("error")
    Else
        Debug.Print("not error")
    End If

如何使用VB.net检测公式的结果是否为错误?

1 个答案:

答案 0 :(得分:2)

这有效:

    If xlApp.WorksheetFunction.IsError(CurrCell) Then
        Debug.Print("error")
    Else
        Debug.Print("not error")
    End If

但是Mike Rosenblum提供了很多better solution

    Public Shared Function IsError(ByVal rgValue As Object) As Boolean
        Return TypeOf (rgValue) Is Int32
    End Function

Dealing with CVErr Values in .NET – Part I: The Problem

Dealing with CVErr Values in .NET – Part II: Solutions