我想知道当我打开Excel中嵌入的Word文档时WINWORD.EXE
是否正在运行。如果它尚未运行,那么我想使用objWord.Quit
。用户可能在Word中工作,我不想干扰它,因此在这种情况下不应该执行objWord.Quit。
我有这个-sniped-代码:
'Variable declaration
Dim objWord As Word.Application
Dim objDoc As Word.Document
objWord
正在实例化如下:
ActiveSheet.OLEObjects(P).Activate
Set objWord = GetObject(, "Word.Application")
在程序结束时:
Set objDoc = Nothing
Set objWord = Nothing
但WINWORD.EXE
实例仍在运行。
如何在程序开始时确定WINWORD.EXE
是否正在运行?
答案 0 :(得分:1)
要拥有一个可以确保用户无法使用的Word实例,请使用New
关键字。与GetObject不同,这将强制启动一个新实例。然后你可以使用objWord.Quit。
Set objWord = New Word.Application
然而 :不是启动Word的实例,也不是使用现有的实例,而是从您的问题描述看来,使用嵌入式文档会更有意义对象,直接。这是一些示例代码:
Sub Test()
Dim ws As Excel.Worksheet
Dim currCel As Excel.Range
Dim oDoc As OLEObject
'to restore the current selection after activating the Word document
Set currCel = Application.Selection
Set ws = ActiveWorkbook.Worksheets("Sheet1")
'Note: I named the embedded document, using code
'If you don't want to do that, you need the index value
'as you have in your code: OLEObjects(P)
Set oDoc = ws.OLEObjects("WordDoc")
WorkWithWordDoc oDoc, currCel
Set oDoc = Nothing
End Sub
Sub WorkWithWordDoc(oDoc As OLEObject, selRange As Excel.Range)
Dim doc As Word.Document
Dim wasActivated As Boolean
Dim cc As Word.ContentControl
'On first opening the Workbook
'the OLE interface of the OLEObject
'isn't accessible, so you need to activate
'it if the error occurs
wasActivated = True
On Error Resume Next
Set doc = oDoc.Object
If Err.Number = 1004 Then
Excel.Application.ScreenUpdating = False
oDoc.Activate
wasActivated = False
Set doc = oDoc.Object
Excel.Application.ScreenUpdating = True
End If
On Error GoTo 0
'Code to work with the document comes here
'Clean up
If Not wasActivated Then
'Deactivate the document
selRange.Select
End If
Set doc = Nothing
End Sub
答案 1 :(得分:0)
使用Word.Documents.Count
:
Function IsWinwordRunning() As Boolean
Dim DCount As Integer
Dim IsWinwordRunning As Boolean
IsWinwordRunning = False
On Error Resume Next
DCount = Word.Documents.Count
If Err = 429 Then DCount = 0
If DCount > 0 Then IsWinwordRunning = True
End Function