为什么这个VBA if语句不起作用?

时间:2014-04-16 15:27:33

标签: vba ms-access

我有这个简单的小块vba代码,我期望它返回"条件二"但它反过来一直到三个"。为什么呢?

Dim testValue as String
testValue = Null

If testValue = 8888 Then
    Debug.Print "Got to condition one"
ElseIf testValue = Null Then
    Debug.Print "Got to condition two"
Else
    Debug.Print "Got to condition three"
End If

2 个答案:

答案 0 :(得分:4)

这里有两件事:

  1. 首先,VBA中的Null表示数据库空值,因此,它不等于任何东西 - 甚至本身。要检查某些内容是否为Null,您必须使用IsNull函数。
  2. 但由于Null适用于数据库,因此可能不是您想要的。您可能希望将testValue设置为Nothing,这是VBA"没有分配值"值。 Nothing也不是简单类型,因此,即使您正在尝试检查某些内容是否为Nothing,您也无法使用=;相反,你应该写ElseIf testValue Is Nothing

答案 1 :(得分:1)

试试这个。您不能将Null放入字符串变量中,您应该在testValue = Null作业中收到错误。

Sub Test()
Dim testValue As Variant
testValue = Null

If testValue = 8888 Then
    Debug.Print "Got to condition one"
ElseIf IsNull(testValue) Then
    Debug.Print "Got to condition two"
Else
    Debug.Print "Got to condition three"
End If
End Sub
相关问题