Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

excel - Check if Word instance is running

I wrote Excel VBA to check whether any instance of Word is already running, but some problems are occurring.

  1. If I open the Word without opening a document, the line If Err.Number = 0 Then wdAppRunning = True returns False.

Open Word via Windows Start

enter image description here

The opened Word instance.

enter image description here

  1. If there is an instance of Word running on a background process, the line also returns False.
  2. If I open Word, and create or open a document, and then run the macro, it returns the expected result (True)

How can I manage the code to identify at least the situation n° 1?

Ps.: the code posted in the link Getting instances of Word and saving documents returns the same situation.

Sub wdAppRunning()
    Dim wdApp As Object
    Dim wdAppRunning As Boolean

    On Error Resume Next
    Set wdApp = GetObject(, "Word.Application")
    If Err.Number = 0 Then wdAppRunning = True

    MsgBox wdAppRunning
    Set wdApp = Nothing

End Sub
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Something like this should work.

Option Explicit

Public Function IsWordRunning() As Boolean
    IsWordRunning = GetObject("winmgmts:\.
ootcimv2").ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'WINWORD.EXE'").Count > 0
End Function

Public Sub Example()
    Debug.Print IsWordRunning()
End Sub

A quick bonus, this could be extended for an Executable name if you like.

Public Function IsProcessRunning(ExecutableName As String) As Boolean
    IsProcessRunning = GetObject("winmgmts:\.
ootcimv2").ExecQuery("SELECT * FROM Win32_Process WHERE Name = '" & ExecutableName & "'").Count > 0
End Function

Example Usage

Public Sub Example()
    Debug.Print IsProcessRunning("WINWORD.EXE")
End Sub

Make sure the name you specify in IsProcessRunning() is the name as it appears in Task Manager.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...