Lotus Notes从UI类切换为COM类出现object variable not set错误
问题原因分析
- 核心错误是对象调用顺序错误:你在
Forward_Email函数中先执行了Set NDocument = Find_Document(NInboxView, findSubjectLike),此时NInboxView还没有经过任何赋值操作,是空对象。传入Find_Document函数后调用空对象的GetFirstDocument方法,自然抛出「object variable not set」错误。赋值NInboxView的遍历逻辑写在了第一次调用Find_Document之后,完全没有生效。 - 存在冗余无效代码:
Set NViewObj = NMailDb.GetView("$Inbox")这行代码没有任何作用,后续你直接把NViewObj作为循环变量遍历视图,值会被直接覆盖。 - 数据库打开存在隐性风险:
NSession.GetDatabase("","",False)的第三个参数为False,代表如果默认邮箱数据库没有提前打开,不会自动执行打开操作,后续操作NMailDb也可能触发空对象错误。
修正后代码
Public Sub Forward_Email(findSubjectLike As String, forwardToEmailAddresses As String) Dim NSession As Object Dim NMailDb As Object Dim NViewObj As Object Dim NInboxView As Object Dim NDocument As Object ' 初始化Notes会话 Set NSession = CreateObject("Lotus.NotesSession") Call NSession.Initialize("") ' 打开默认邮箱数据库,补充打开校验 Set NMailDb = NSession.GetDatabase("", "", False) If Not NMailDb.IsOpen Then Call NMailDb.Open("", "") End If ' 先找到收件箱文件夹再调用查询逻辑 For Each NViewObj In NMailDb.Views If NViewObj.IsFolder And NViewObj.Name = "($Inbox)" Then Set NInboxView = NViewObj Exit For End If Next ' 确认收件箱对象初始化成功再调用查询 If Not NInboxView Is Nothing Then Set NDocument = Find_Document(NInboxView, findSubjectLike) End If ' 后续转发逻辑自行补充 End Sub Private Function Find_Document(NView As Object, findSubjectLike As String) As Object Dim NThisDoc As Object Dim thisSubject As String Set Find_Document = Nothing Set NThisDoc = NView.GetFirstDocument While Not NThisDoc Is Nothing And Find_Document Is Nothing thisSubject = NThisDoc.GetItemValue("Subject")(0) ' 完全匹配逻辑,如果需要模糊匹配替换为下一行注释内容 If LCase(thisSubject) = LCase(findSubjectLike) Then Set Find_Document = NThisDoc ' If InStr(LCase(thisSubject), LCase(findSubjectLike)) > 0 Then Set Find_Document = NThisDoc Set NThisDoc = NView.GetNextDocument(NThisDoc) Wend End Function
额外优化建议
- 你代码中声明的
NUIWorkspace、NUIDocument、NFwdUIDocument三个UI类变量完全没有使用,如果你确定不需要用到UI交互逻辑可以直接删除,避免冗余。 - 当前
Find_Document内的匹配逻辑是完全匹配主题,如果需要实现参数名对应的模糊匹配(包含指定关键词即可),可以替换代码中注释的匹配逻辑。
内容的提问来源于stack exchange,提问作者Drawleeh
相关产品推荐
相关产品推荐

