Visual Studio开发.NET程序对接Office 365 Word报错求助
问题概述
原基于Visual Studio 2015 + .NET开发的Word 2013对接应用,可通过书签创建文档、填充文本/表格数据,运行正常。升级至Office 365后,程序初始化Word实例时抛出COM注册错误。
已执行操作
已添加以下引用:
- Microsoft.Office.Interop.Word
- Microsoft.Office.Core
- Microsoft Office 16.0 Object Library
错误详情
COMException was unhandled
An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll
Additional information: Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
错误触发代码行:Dim appWord As New Word.Application
涉事代码示例
Imports Microsoft.Office.Core Imports Microsoft.Office.Interop Private Sub word_Click(sender As Object, e As EventArgs) Handles word.Click Dim appWord As New Word.Application Dim docWord As New Word.Document docWord = appWord.Documents.Add("s:\direct\ph1English.docx") appWord.Visible = True End Sub
解决方案
1. 匹配项目平台与Office 365位数
Office 365默认安装为64位,若VS项目平台目标为32位(x86),会因位数不匹配导致CLSID无法找到:
- 打开项目属性 → 生成选项卡 → 将平台目标改为
x64(与Office 365位数一致) - 若业务必须使用32位程序,需卸载当前64位Office 365,重新安装32位版本
2. 重新注册Word COM组件
以管理员身份启动命令提示符,执行对应位数的注册命令:
- 64位Office:
regsvr32.exe "C:\Program Files\Microsoft Office\Root\Office16\MSWORD.OLB" - 32位Office:
regsvr32.exe "C:\Program Files (x86)\Microsoft Office\Root\Office16\MSWORD.OLB"
3. 修复Office 365安装
- 打开控制面板 → 程序和功能
- 找到
Microsoft 365,右键选择更改 - 选择快速修复(优先尝试),若无效则选择在线修复,完成后重启电脑
4. 改用后期绑定减少版本依赖
避免直接引用特定版本的Interop组件,改用后期绑定方式创建Word实例,兼容性更强:
Imports System.Reflection Private Sub word_Click(sender As Object, e As EventArgs) Handles word.Click Dim appWord As Object = Activator.CreateInstance(Type.GetTypeFromProgID("Word.Application")) Dim docWord As Object = appWord.Documents.Add("s:\direct\ph1English.docx") appWord.Visible = True End Sub
内容的提问来源于stack exchange,提问作者F L

