NotesDocument 作为函数返回值的问题

先看如下代码:

    ‘some code ……
‘Set my doc with the return value from the function…
Set recipientDoc = getDocInNAB(“search string”)

If Not recipientDoc Is Nothing Then
‘In debug I end up here
Else
‘When I run it I end up here….
Print “ERROR”
End If
‘some code ……

Function getDocInNAB(y As String) As NotesDocument
Dim nabs As Variant
Dim v As NotesView
Dim match As NotesDocument
Dim i As NotesItem
nabs = s.AddressBooks

Forall x In nabs
‘Get handle on Directory to search
Call x.Open(x.Server, x.FilePath)
Set v = x.GetView(“($Users)”)
Set match = v.GetDocumentByKey(y,True)

If Not match Is Nothing Then
Print “Found ————> ” & y
Set getDocInNAB = match
Else
Set getDocInNAB = Nothing
End If
End Forall
End Function

函数 getDocInNAB 实现了一个功能:通过参数 y 来查找个人文档,然后将查找结果返回。初看上去好像没什么问题,实际上这个函数的返回值一直是 Nothing。

问题的原因是,NAB 数据库对象是在函数内定义的,当文档作为返回值传递给调用者时,其 Parent 数据库对象已经销毁,所以这个文档也就是 Nothing 了。

解决的办法:将数据库一起作为参数传递过去或者定义为全局变量。