在VBA中关闭/释放Word对象?

Ana*_*tic 6 vba ms-word excel-2007 excel-vba word-vba

我有以下代码打开我开发的Excel工作簿应用程序的手册:

Sub OpenManual()

'Word.Application.Documents.Open "\\filePath\FormFlow To MSExcel\FeedSampleReport-Manual.docx"

Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True

objWord.Documents.Open "\\filePath\FormFlow To MSExcel\FeedSampleReport-Manual.docx"

End Sub
Run Code Online (Sandbox Code Playgroud)

这给了我两个问题:

  1. 该文档打开,但在后台.用户不知道文档已打开,除非他们知道在任务栏中检查Microsoft Word.
  2. 当我尝试关闭我收到的word文档时: 此文件正由另一个应用程序或用户使用.(C:\用户\我\ AppData的... \的Normal.dotm)

当我在该对话框上单击"确定"时,我会收到"另存为"屏幕.

如果我取消了并尝试关闭空白的Microsoft Word实例,那么我得到:

已经进行了影响全局模板Normal的更改.你想保存这些变化吗?

然后如果我点击否,一切都会终止.

有谁可以帮我解决这两个问题?我需要以某种方式释放对象吗?以前从未见过这个.

编辑:

尝试@ Layman-Coders方法后:

Sub OpenManual()
'Word.Application.Documents.Open "\\filePath\FormFlow To MSExcel\FeedSampleReport-Manual.docx"

'Open an existing Word Document from Excel
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True

' Should open as the forefront
objWord.Activate

'Change the directory path and file name to the location
'of the document you want to open from Excel
objWord.Documents.Open "\\filePath\FormFlow To MSExcel\FeedSampleReport-Manual.docx"

objWord.Quit
Set objWord = Nothing

End Sub
Run Code Online (Sandbox Code Playgroud)

当我打开另一个word文档并单击按钮时,会发生以下情况:

  1. 手册在最前面打开,但我马上就收到了 This file is in use by another application or user. (C:\Users\Me\AppData\...\Normal.dotm)
  2. 我按OK并收到另存为对话框.
  3. 取消"另存为"对话框并显示我的"手册"文档.
  4. 当我单击红色X以关闭文档时,我收到Changes have been made that affect the global template, Normal. Do you want to save those change?我单击否并关闭文档.

如果这个文件是我打开的第一个单词实例:

  1. 该文件打开.
  2. 一旦代码点击该objWord.Quit行,文档立即关闭.

我只是希望文档打开到最前端,允许用户在需要时查看手册以获得帮助,并让他们自行决定关闭文档.

Cub*_*ase 11

因此,您使用Word要求您保存全局模板的问题是因为已经有一个Word打开的副本,它具有Normal模板的权限.当您使用CreateObject设置Word对象时,您第二次加载Word,将普通模板打开为只读.

您需要做的是检查Word是否打开以及是否抓取Word的副本.如果不是那么你可以打开Word.

Sub OpenManual()
    Dim objWord As Object

    'We need to continue through errors since if Word isn't
    'open the GetObject line will give an error
    On Error Resume Next
    Set objWord = GetObject(, "Word.Application")

    'We've tried to get Word but if it's nothing then it isn't open
    If objWord Is Nothing Then
        Set objWord = CreateObject("Word.Application")
    End If

    'It's good practice to reset error warnings
    On Error GoTo 0

    'Open your document and ensure its visible and activate after openning
    objWord.Documents.Open "\\filePath\FormFlow To MSExcel\FeedSampleReport-Manual.docx"
    objWord.Visible = True
    objWord.Activate

    Set objWord = Nothing
End Sub
Run Code Online (Sandbox Code Playgroud)

另一个很好的代码是压制显示警报.这将停止显示"您要保存"类型对话框.

objWord.DisplayAlerts = 0