【问题标题】:Why is this VBA if statement not working?为什么这个 VBA if 语句不起作用?
【发布时间】:2014-04-16 15:27:32
【问题描述】:

我有一段简单的 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

【问题讨论】:

  • 第二行出现错误,Null 的使用无效(您不能将其分配给字符串。
  • 使用IsNull 来检查Null
  • Textbox null problem的可能重复

标签: vba ms-access


【解决方案1】:

这里发生了两件事:

  1. 首先,Null 在 VBA 中表示数据库空值,因此它不等于任何东西——甚至它本身。要检查某个东西是否为Null,您必须使用IsNull 函数。
  2. 但由于Null 用于数据库,它可能不是您想要的。您可能希望将testValue 设置为Nothing,这是VBA“未分配值”的值。 Nothing 也不是一个简单的类型,所以即使你想检查某个东西是否是Nothing,你也不能使用=;相反,你应该写ElseIf testValue Is Nothing

【讨论】:

  • 1) 这里的None 是什么:Set testValue = None?它不编译。 2)您不能将Set testValuetestValue Is NothingDim testValue As String 一起使用
  • @simoco 我刚刚删掉了代码 sn-p;我在日常工作中编写 Python,基本上写了一个可爱的 VBA 和 Python 混合体。对此感到抱歉。
  • 没问题,但是你的第二个项目还是不行:你不能测试testValue Is Nothing 如果testValueString 类型..
【解决方案2】:

试试这个。您不能将 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多