如何在 Access 2010 VBA 中封装 IIF 和 ISNULL 调用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11465977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to encapsulate IIF and ISNULL call in Access 2010 VBA?
提问by Earth Engine
I use the following expression pattern in my Access 2010 database frequently:
我经常在 Access 2010 数据库中使用以下表达式模式:
IIF(ISNULL(fieldName), Null, myFunction(fieldName))
Here myFunction is a user defined function that turns the value of fieldName into another format, if it does exists.
这里 myFunction 是一个用户定义的函数,它将 fieldName 的值转换为另一种格式(如果确实存在)。
Just for a little bit reduce of typing, I tried to define the following function:
只是为了稍微减少打字,我尝试定义以下函数:
Function IifIsNull(p AS Variant, v AS Variant) AS Variant
If IsNull(p) Then IifIsNull = p Else IifIsNull = v
End Function
and I supposed to use it in the following way:
我应该按以下方式使用它:
IifIsNull(fieldName, myFunction(fieldName))
But it does not work. When fieldName
is Null, the return value of the IifIsNull
is #Error
, and IifIsNull
has even not been called!
但它不起作用。当fieldName
为 Null 时,返回值IifIsNull
是#Error
,IifIsNull
甚至还没有被调用过!
Is it possible to simplify the given code pattern with a user defined function or system function at all?
是否可以使用用户定义的函数或系统函数来简化给定的代码模式?
UPDATE:
更新:
There are a couple of myFunction
s, and all of those functions are currently strongly typed, a simple example is the following:
有几个myFunction
s,所有这些函数目前都是强类型的,一个简单的例子如下:
Function RemoveSpace(str AS String) AS String
For i=1 to Len(str)
If Mid(str,i,1) <> " " Then RemoveSpace = RemoveSpace + Mid(str,i,1)
Next
End Function
回答by Jean-Fran?ois Corbett
I assume that myFunction(fieldName)
throws an error when fieldName
is null.
我假设myFunction(fieldName)
当fieldName
为空时会引发错误。
When you call IifIsNull(fieldName, myFunction(fieldName))
, the first thing that gets evaluated is myFunction(fieldName)
. So if fieldName
is null, you get an error.
当您调用时IifIsNull(fieldName, myFunction(fieldName))
,首先评估的是myFunction(fieldName)
。所以如果fieldName
为空,你会得到一个错误。
回答by Fionnuala
Why not simply evaluate fieldname in MyFunction?
为什么不简单地在 MyFunction 中评估 fieldname?
Append an empty string to field name to ensure it always passes a string, not a null.
将一个空字符串附加到字段名称以确保它始终传递一个字符串,而不是一个空值。
=MyFunction(FieldName & "")
Function MyFunction(Fieldname) As Variant
''Depending on what your function does, it is may not necessary to check
If FieldName<>"" Then
MyFunction = FieldName & " was here"
End If
End Function