【发布时间】:2017-04-04 05:41:28
【问题描述】:
我正在从 Excel 自动化 Word 并使用以下代码。当我第一次运行代码时,我总是能够毫无问题地运行它。但是,在第二种情况下,我总是会收到此错误。然后我必须手动关闭Word文件并再次运行代码,它第一次运行顺利,第二次我再次看到错误。
'On Error Resume Next
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
Dim intChoice As Integer
Dim strPath As String
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intChoice = Application.FileDialog(msoFileDialogOpen).Show
If intChoice <> 0 Then
'get the path selected
strPath = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)
'opens the document
Set objdoc = objWord.Documents.Open(strPath)
With Documents(objdoc) '''This is where error points to in yellow '''
Set myrange = ActiveDocument.Content
''' My execution code here
end with
objWord.ActiveDocument.SaveAs ThisWorkbook.Path & "\" &
ActiveSheet.Range("E3").Value & "_MVR"
'objWord.ActiveDocument.Close
objdoc.Close
objWord.Quit
Set objdoc = Nothing
Set objWord = Nothing
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
【问题讨论】:
-
由于您的代码没有缩进,因此您“错过”了错误的原因。您正在 If 语句
If intChoice <> 0 Then中“释放” Word 对象Set objWord = Nothing。但是,无论如何都会创建Set objWord = CreateObject("Word.Application"),只需将Set objWord = Nothing移到If之外,它就会关闭您创建的新 Word 实例。 -
我尝试了您建议的更改,但仍然出现相同的错误。
标签: excel runtime-error ms-word vba