VBA 中的“null”概念(在NullReferenceException
-null的意义上,如果您熟悉 C# 或NullPointerException
在 Java 中)包含在关键字中Nothing
。这适用于 VB6(及更早版本)以及 VB.NET。
Dim foo As Object
Debug.Print foo.Bar ' boom, the dreaded runtime error 91 shows up
Run Code Online (Sandbox Code Playgroud)
所以你的解释Nothing
是正确的。
与 Java 或 C# 相反,您不能使用比较运算符(==
在 C#/Java 中,=
在 VBA 中)在 VBA 中进行空检查,因此(以类似于 SQL 的方式),您使用Is
关键字:
If foo Is Nothing Then ' if (foo == null) { }
Run Code Online (Sandbox Code Playgroud)
或者否定形式:
If Not foo Is Nothing Then ' if (foo != null) { }
Run Code Online (Sandbox Code Playgroud)
请注意,此公式无效,因为Nothing
无法否定:
If foo Is Not Nothing Then ' incorrect formulation, if (foo == !null) { }
Run Code Online (Sandbox Code Playgroud)
事情变得泥泞和混乱,当你意识到VBA具有的IsNull
功能....然后还IsEmpty
和相应的Null
,vbNull
,Empty
和vbEmpty
值-但这些都是外面你的问题的范围,并在MSDN和堆栈溢出很容易找到。