我试图使用Excel VBA保存Word文档,但我收到错误“ActiveX组件无法创建对象” .
当我调试时,错误来自以下行: Set wrdApps = CreateObject("Word.Application")
. 它工作正常,但它刚刚开始给我这个错误 . 有谁知道如何解决这一问题?谢谢您的帮助!
Sub saveDoc()
Dim i As Integer
For i = 1 To 2661:
Dim fname As String
Dim fpath As String
With Application
.DisplayAlerts = False
.ScreenUpdating = False
.EnableEvents = False
End With
fname = ThisWorkbook.Worksheets(3).Range("H" & i).Value
fpath = ThisWorkbook.Worksheets(3).Range("G" & i).Value
Dim wrdApps As Object
Dim wrdDoc As Object
Set wrdApps = CreateObject("Word.Application")
'the next line copies the active document- the ActiveDocument.FullName
' is important otherwise it will just create a blank document
wrdApps.documents.Add wrdDoc.FullName
Set wrdDoc = wrdApps.documents.Open(ThisWorkbook.Worksheets(3).Range("f" & i).Value)
' do not need the Activate, it will be Activate
wrdApps.Visible = False
' the next line saves the copy to your location and name
wrdDoc.SaveAs "I:\Yun\RTEMP DOC & PDF\" & fname
'next line closes the copy leaving you with the original document
wrdDoc.Close
On Error GoTo NextSheet:
NextSheet:
Resume NextSheet2
NextSheet2:
Next i
With Application
.DisplayAlerts = True
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
4 回答
wrdDoc初始化了吗?您是否在设置对象之前尝试使用wrdDoc?
第一行应该是注释中的ActiveDocument.FullName吗?所以:
检查是否在 Tools > References 中勾选了Microsoft Excel对象库和Microsoft Office对象库,并且已经注册了它们 .
如果勾选了它们,则可能需要从“Excel帮助”菜单中运行“检测并修复”,以确保Office安装没有以任何方式损坏 .
当我带着我的VBA脚本时,从Windows 7升级到10时遇到了问题 . 仍然不确定错误的根本原因是什么,但同时这段代码对我有用 . 这是一种解决方法,它限制了Word(或Outlook / Excel)已处于打开(手动)状态的需要,但如果您设置了引用,则应允许脚本运行 . 只需将
"CreateObject("
更改为"GetObject(, "
即可 . 这将告诉系统使用已经打开的窗口 .要使用的完整代码是:
试试这个..我已经遇到了很多时间......
所以我只需通过搜索它(位于任务栏上)运行我的excel,然后右键单击然后“以管理员身份运行”或者如果您已经创建了excel文件,则从文件>打开>浏览打开它 . 避免双击excel文件直接打开 .