Function VB在VB函数中使用ADO记录集,检查是否为null
我有一些奇怪的行为让我困惑。我在vb(vb的Microsoft Word宏版本)中创建了一个函数,如下所示:Function VB在VB函数中使用ADO记录集,检查是否为null,function,vba,Function,Vba,我有一些奇怪的行为让我困惑。我在vb(vb的Microsoft Word宏版本)中创建了一个函数,如下所示: Public Function isitnullorempty(newstring As String) As Boolean If IsNull(newstring) Or IsEmpty(newstring) Or newstring = "" Then isitnullorempty = False Else isitnullorem
Public Function isitnullorempty(newstring As String) As Boolean
If IsNull(newstring) Or IsEmpty(newstring) Or newstring = "" Then
isitnullorempty = False
Else
isitnullorempty = True
End If
End Function
If IsNull(oRecordset.Fields("CustomerTypeRefFullName").Value) Or IsEmpty(oRecordset.Fields("CustomerTypeRefFullName").Value) Or oRecordset.Fields("CustomerTypeRefFullName").Value = "" Then
MsgBox "potato"
End If
如果我创建一个变量,然后将其设置为null,“”,或者将其保留为空,那么它似乎可以按预期工作。我操纵变量,然后执行MSGBOX isitnullorempty(变量),它响应我的期望。但是,当我将记录集放入函数中时,它的行为方式不同。我甚至试着让一个变量将其设置为记录集,然后测试它,但这也不起作用。如果我尝试调用以下命令
'ADO query code here (This is an ODBC connection)
DO While (Not oRecordset.EOF)
MsgBox isitnullorempty(oRecordset.Fields("CustomerTypeRefFullName"))
oRecordset.MoveNext
Loop
这会产生错误:Null的使用无效
所以有两个问题
是否已经有一个vb函数存在,它符合我的要求?
为什么我的代码会这样
更奇怪的是,如果我在函数之外单独进行测试,它就会工作
临时解决方案
它编写的代码比需要的要多,但由于我似乎无法使用记录集值调用函数,因此我将根据我的需要单独检查每条记录,如下所示:
Public Function isitnullorempty(newstring As String) As Boolean
If IsNull(newstring) Or IsEmpty(newstring) Or newstring = "" Then
isitnullorempty = False
Else
isitnullorempty = True
End If
End Function
If IsNull(oRecordset.Fields("CustomerTypeRefFullName").Value) Or IsEmpty(oRecordset.Fields("CustomerTypeRefFullName").Value) Or oRecordset.Fields("CustomerTypeRefFullName").Value = "" Then
MsgBox "potato"
End If
在我看来,你的逻辑是错误的: 如果IsNull(newstring)或IsEmpty(newstring)或newstring=“” 然后
isitnullorempty=False
否则
isitnullorempty=True
如果结束 难道不是吗 如果IsNull(newstring)或IsEmpty(newstring)或newstring=“” 然后 isitnullorempty=TRUE 否则 isitnullorempty=FALSE
结束如果答案是如果要将null传递给函数的参数,则需要将该参数设置为变量。
作为布尔函数的公共函数是完全或空的(newstring作为变量)您是否尝试过更显式地使用.Fields(“CustomerTypeRefFullName”).Value?现在,从技术上讲,您传入的是一个Field对象,而不是它的值…isitnullorempty=(Len(newstring&“”)=0)这是一个很好的猜测,但没有做到这一点-isitnullorempty(oRecordset.Fields(“CustomerTypeRefFullName”).Value)-没有起作用,但这是一个很好的猜测。我假设如果-MsgBox或cordset.Fields(“CustomerTypeRefFullName”)-有效,我不必显式调用它的值。恐怕我不明白你的第二个评论??这是一个替换isitnullorempty函数体的建议。哈哈,根据输入,它将是1或0?!哈哈,哇,太好了。:)呵呵,是的,我注意到我问了这个问题,但回答是否定的。不管我是否返回true或false,但它不应该运行吗?感谢您指出,我将更改它。我将使用Tim的第一个选项,显式地从测试字段中获取值。如果仍然抛出错误,请尝试将该值转换为字符串。1 Dim testvar为string 2 testvar=oRecordset.Fields(“CustomerTypeRefFullName”)。值3 MsgBox isitnullorempty(testvar)我仍然收到错误。这真的很奇怪…也许这是显而易见的,但字段CustomerTypeRefFullName是什么数据类型?根据这个函数,vb不是我常用的语言:它是Null(没有有效数据)