Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...