我最近试图Nz(Value, [ValueIfNull])
在Excel中重新定义Access的功能,因为我发现它非常有用但它在Excel中不存在(因为我发现在移动一些有用的函数时我很失望).Access的Nz函数检查Value
- 如果此值为null,则返回ValueIfNull
(否则返回Value
).在Access中,它对于检查输入框的值(以及其他几个方面)非常有用:
If Nz(myTextBox.Value, "") = "" Then MsgBox "You need to enter something!" End If
滚动我自己的Nz
功能似乎并不困难:
Public Function Nz(value As Variant, Optional valueIfNull As Variant = "") As Variant If IsNull(value) Then Nz = valueIfNull Else Nz = value End If End Function
但是一旦我尝试用任何实际上为空的东西调用它,Excel就会在调用行上抱怨它(Run-time error '91': Object variable or With block not set
我理解它与NullReferenceException
其他语言大致相同),甚至在进入Nz函数体之前.例如,Nz(someObj.Value, "")
只有在someObj.Value
不为null 时才会起作用(使函数完全没有用).
我在这里错过了VBA的一些细节吗?来自VB.NET之类的语言,看起来很混乱 - 我理解对象引用只是驻留在内存中的实际对象的地址,因此传递引用(而不是对象)不应该导致问题(直到你尝试实际上,当然对不存在的对象做一些事情.例如:
Dim myObj As SomeObject SomeMethod(myObj) 'the call itself is fine Public Sub SomeMethod(SomeObject obj) myObj.DoSomething() 'but *here* it would crash End Sub
如何在VBA中创建接受空参数的子函数?
看到this
和that
如果有什么还不清楚,并尝试
Sub Main() Dim obj As Range Debug.Print Nz(obj) Dim v As Variant v = Null Debug.Print Nz(v) End Sub Public Function Nz(value As Variant, Optional valueIfNull As Variant = "") As Variant ' deal with an object data type, vbObject = 9 If VarType(value) = vbObject Then If value Is Nothing Then Nz = valueIfNull Else Nz = value End If ' deal with variant set to null, vbNull is a Variant set to null ElseIf VarType(value) = vbNull Then If IsNull(value) Then Nz = valueIfNull Else Nz = value End If End If End Function