Outlook VBA模态用户窗体下调用GetInspector报错求助
问题描述
- 已解决模块间变量传递问题,但遇到新问题:点击新建邮件按钮触发用户窗体显示后,邮件窗口会直接覆盖窗体。
- 将用户窗体设为模态(移除
.Show后的False参数)后,仅能显示窗体,但执行MyNewEmail过程时,Set objInsp = msg.GetInspector语句报错;非模态窗体时无此问题。 - 根据论坛信息,
GetInspector需要调用已显示的MailItem,但尝试主动显示邮件窗口也触发错误。 - 尝试过两种方案均失败:
a) 尝试让新邮件的Inspector窗口可见,但无法正确识别该窗口;
b) 使用非模态窗体并尝试最小化新邮件窗口,结果误将Outlook主窗口最小化。
相关代码
1. NewInspector事件代码
Private Sub objInsp_NewInspector(ByVal Inspector As Inspector) Dim frm As frmNewEmail Dim msg As Outlook.MailItem If TypeName(Inspector.CurrentItem) = "MailItem" Then If Inspector.CurrentItem.Subject <> "" Then Exit Sub 'This procedure is only for new email mesages End If Set frm = New frmNewEmail With frm Set .Message = Inspector.CurrentItem .StartUpPosition = 2 .Show False End With End If End Sub
2. 报错代码段
If msg.Class = olMail Then Set objInsp = msg.GetInspector '<<< Throws an error if userform = Modal If objInsp.EditorType = olEditorWord Then If objInsp.CurrentItem.BodyFormat <> olFormatHTML Then objInsp.CurrentItem.BodyFormat = olFormatHTML End If End If Else Exit Function End If
解决办法
方案1:模态窗体下的兼容处理
核心思路是先确保邮件的Inspector实例初始化完成,再调用GetInspector,同时调整窗口显示顺序避免覆盖:
- 修改报错代码段:
If msg.Class = olMail Then ' 先强制显示邮件窗口,触发Inspector实例初始化 msg.Display ' 短暂延迟确保窗口加载完成(可根据实际情况调整时长) Application.Wait (Now + TimeValue("0:00:01")) Set objInsp = msg.GetInspector If objInsp.EditorType = olEditorWord Then If objInsp.CurrentItem.BodyFormat <> olFormatHTML Then objInsp.CurrentItem.BodyFormat = olFormatHTML End If End If ' 暂时隐藏邮件窗口,避免干扰用户窗体 msg.Visible = False Else Exit Function End If
- 修改
NewInspector事件代码:
Private Sub objInsp_NewInspector(ByVal Inspector As Inspector) Dim frm As frmNewEmail Dim msg As Outlook.MailItem If TypeName(Inspector.CurrentItem) = "MailItem" Then If Inspector.CurrentItem.Subject <> "" Then Exit Sub 'This procedure is only for new email mesages End If Set msg = Inspector.CurrentItem ' 先隐藏邮件窗口 msg.Visible = False Set frm = New frmNewEmail With frm Set .Message = msg .StartUpPosition = 2 .Show ' 模态显示窗体 End With ' 窗体关闭后再显示邮件窗口 msg.Display End If End Sub
方案2:非模态窗体下精准控制邮件窗口
针对之前误最小化主窗口的问题,直接通过Inspector对象操作新建邮件的窗口,而非全局操作:
修改NewInspector事件代码:
Private Sub objInsp_NewInspector(ByVal Inspector As Inspector) Dim frm As frmNewEmail Dim msg As Outlook.MailItem If TypeName(Inspector.CurrentItem) = "MailItem" Then If Inspector.CurrentItem.Subject <> "" Then Exit Sub 'This procedure is only for new email mesages End If Set msg = Inspector.CurrentItem ' 仅最小化当前新建邮件的Inspector窗口,不影响主窗口 Inspector.WindowState = olMinimized Set frm = New frmNewEmail With frm Set .Message = msg .StartUpPosition = 2 .Show False ' 非模态显示窗体 End With End If End Sub
内容的提问来源于stack exchange,提问作者Art
相关产品推荐
相关产品推荐

