VBScript中的空值错误检查

32

我在一个经典ASP页面中有以下VBScript代码:

function getMagicLink(fromWhere, provider)
    dim url 
    url = "magic.asp?fromwhere=" & fromWhere
    If Not provider is Nothing Then ' Error occurs here
        url = url & "&provider=" & provider 
    End if
    getMagicLink = "<a target='_blank' href='" & url & "'>" & number & "</a>"
end function

在代码行 If Not provider Is Nothing Then 上,我不断收到一个“对象必需”错误信息。

值要么是NULL,要么不是NULL,那么为什么会出现这个错误?

编辑:当我调用该对象时,我传入的要么是NULL,要么是一个字符串。

3个回答

42

从您的代码来看,provider 看起来是一个变量或其他类型,而不是一个对象。

Is Nothing 仅适用于对象,但后面你说它是一个应该是 NULL 或 NOT NULL 的值,这应该由 IsNull 处理。

尝试使用:

If Not IsNull(provider) Then 
    url = url & "&provider=" & provider 
End if

或者,如果那样行不通,尝试:

If provider <> "" Then 
    url = url & "&provider=" & provider 
End if

1
我尝试使用 If Not IsNull(provider) Then,但是页面在 url = url & "&provider=" & provider 行上引发了异常。错误显示为“对象变量未设置”。 - Vivian River
这真是一个让人费解的问题。你是将 vbNull 传递给了 provider,还是其他什么东西? - LittleBobbyTables - Au Revoir
1
我一直被教导说,“Nothing”只适用于对象,尝试传入“vbNull”代替。在VBScript中,“Nothing”<>“Null”。 - LittleBobbyTables - Au Revoir
1
使用Null而不是vbNullvbNull是与VarType函数一起使用的常量。 - Cheran Shunmugavel

24

我看到评论中有很多混淆。 NullIsNull()vbNull主要用于数据库处理,并且通常不在VBScript中使用。如果调用对象/数据的文档中没有明确说明,请勿使用。

要测试变量是否未初始化,请使用IsEmpty()。要测试变量是否未初始化或包含"",请测试""Empty。要测试变量是否为对象,请使用IsObject,若此对象无引用,请测试Is Nothing

在您的情况下,您首先要测试变量是否为对象,然后查看该变量是否为Nothing,因为如果它不是对象,则在测试Nothing时会出现“需要对象”错误。

可在您的代码中混合和匹配的片段:

If IsObject(provider) Then
    If Not provider Is Nothing Then
        ' Code to handle a NOT empty object / valid reference
    Else
        ' Code to handle an empty object / null reference
    End If
Else
    If IsEmpty(provider) Then
        ' Code to handle a not initialized variable or a variable explicitly set to empty
    ElseIf provider = "" Then
        ' Code to handle an empty variable (but initialized and set to "")
    Else
        ' Code to handle handle a filled variable
    End If
End If

1
我只需要在变量末尾添加一个空白("")并进行比较。以下类似的内容应该可以在变量为空时工作。您还可以修剪变量,以防有空格。
If provider & "" <> "" Then 
    url = url & "&provider=" & provider 
End if

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接