New Outlook.Application报-2147319799(8002801d)运行时错误问题咨询
问题背景
编写了如下用于保存Outlook附件的VBA代码:
Sub SaveOutlookAtachments() Dim ol As Outlook.Application Dim ns As Outlook.Namespace Dim fol As Outlook.Folder Dim i As Object Dim mi As Outlook.MailItem Set ol = New Outlook.Application Set ns = ol.GetNamespace("MAPI") Set fol = ns.Fs.Folders(1).Folders("my_folder") For Each i In fol.Items If i.Class = olMail Then Set mi = i Debug.Print mi.SenderName, mi.ReceivedTime, mi.Attachments.Count End If Next i End Sub
运行代码时触发报错:
运行时错误“-2147319799(8002801d)”
自动化错误:库未注册
调试定位到触发报错的代码行为:
Set ol = New Outlook.Application
常规排查思路中该报错多为项目未添加Outlook对应引用导致,但当前已经在项目引用中勾选了Outlook Object Library,仍无法解决问题。
解决方法
按优先级依次尝试以下方案即可解决问题:
- 修复Office安装:库未注册报错大概率是Office安装过程中COM组件注册信息损坏导致,和是否勾选引用无直接关联。关闭所有Office相关进程,打开控制面板的「程序和功能」列表,找到已安装的Microsoft Office条目,点击「更改」,先执行「快速修复」,完成后重启设备测试代码;如果快速修复无效,再执行「联机修复」即可修复损坏的注册信息。
- 手动注册Outlook类型库:如果修复Office无效,可以通过regsvr32命令手动注册Outlook的类型库文件。按
Win+R打开运行窗口,根据自身Office安装的版本和路径执行对应命令:- 64位Office,或32位系统安装32位Office:执行
regsvr32.exe "C:\Program Files\Microsoft Office\root\Office16\MSOUTL.OLB" - 64位系统安装32位Office:执行
regsvr32.exe "C:\Program Files (x86)\Microsoft Office\root\Office16\MSOUTL.OLB"
注:路径中的Office16对应Office 2016/2019/2021/365版本,Office 2013对应Office15,Office 2010对应Office14,根据自身实际安装版本修改路径中的版本号即可,执行后弹出注册成功提示即操作完成。
- 64位Office,或32位系统安装32位Office:执行
- 改用晚绑定写法规避引用依赖:如果不想处理组件注册问题,可以直接放弃早绑定引用,改用晚绑定方式创建Outlook对象,不需要提前勾选Outlook Object Library引用即可运行,修改后的可运行代码如下:
Sub SaveOutlookAtachments() Dim ol As Object Dim ns As Object Dim fol As Object Dim i As Object Dim mi As Object Const olMail As Integer = 0 Set ol = CreateObject("Outlook.Application") Set ns = ol.GetNamespace("MAPI") ' 修正原代码笔误:Namespace对象不存在Fs属性,直接访问Folders集合即可 Set fol = ns.Folders(1).Folders("my_folder") For Each i In fol.Items If i.Class = olMail Then Set mi = i Debug.Print mi.SenderName, mi.ReceivedTime, mi.Attachments.Count End If Next i ' 释放对象资源 Set mi = Nothing Set i = Nothing Set fol = Nothing Set ns = Nothing Set ol = Nothing End Sub
额外提醒:原代码中ns.Fs.Folders(1)为笔误,Outlook的Namespace对象下没有Fs属性,解决库注册问题后也需要修正该处写法,否则会触发「对象不支持该属性或方法」的报错。
内容的提问来源于stack exchange,提问作者Alexandros
相关产品推荐
相关产品推荐

