我有以下代码打开我开发的Excel Workbook应用程序的手册:
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
这给了我两个问题:
当我在该对话框上单击“确定”时,我会收到“另存为”屏幕。
如果我取消了并尝试关闭空白的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
当我打开另一个word文档并单击按钮时,会发生以下情况:
This file is in use by another application or user. (C:\Users\Me\AppData\...\Normal.dotm)
Changes have been made that affect the global template, Normal. Do you want to save those change?
我点击否,文档将关闭。如果这个文件是我打开的第一个单词实例:
objWord.Quit
行,文档就会立即关闭。我只是希望将文档打开到最前端,以便用户在需要时查看手册以获得帮助,并让他们自行决定是否关闭文档。
答案 0 :(得分: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
另一个很好的代码是压制显示警报。这将停止显示“您要保存”类型对话框。
objWord.DisplayAlerts = 0
答案 1 :(得分:2)
尝试这样的事情:
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.Activate 'Should make it the forefront (1)
objWord.Documents.Open "\\filePath\FormFlow To MSExcel\FeedSampleReport-Manual.docx"
'If you just want to close it afterwards...
objWord.Quit 'Changes are discarded
'Either way, you should have the following somewhere
Set objWord = Nothing
End Sub
将对象设置为空,应取消连接
答案 2 :(得分:0)
我遇到了同样的问题。只有下面的代码关闭了这个Word窗口:
Dim X As Variant
X = Shell("powershell.exe kill -processname winword", 1)
中找到了此代码