Word application 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

Cindy Meister's user avatar

asked Jan 26, 2020 at 11:34

Carlos Matioli's user avatar

11

Something like this should work.

Option Explicit

Public Function IsWordRunning() As Boolean
    IsWordRunning = GetObject("winmgmts:\.rootcimv2").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:\.rootcimv2").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.

answered Jan 27, 2020 at 17:29

Ryan Wildry's user avatar

Ryan WildryRyan Wildry

5,5921 gold badge16 silver badges35 bronze badges

1

Alternatively you can try with

Public Function Is_Word_Running() As Boolean

   Dim WMG As Object, Proc As Object

    Is_Word_Running = False
    Set WMG = GetObject("winmgmts:")
    For Each Proc In WMG.InstancesOf("win32_process")
        If UCase(Trim(Proc.Name)) = "WINWORD.EXE" Then
            Is_Word_Running = True
            Exit For
        End If
    Next Proc
    Set WMG = Nothing

End Function

answered Jan 27, 2020 at 13:43

Zer0Kelvin's user avatar

Zer0KelvinZer0Kelvin

3142 silver badges7 bronze badges

1

Try this

    Public Function Is_Word_Running() As Boolean

       Dim Wrd As Object

       On Error Resume Next
       Set Wrd = GetObject(, "Word.Application")
       On Error GoTo 0
       Is_Word_Running = Not Wrd Is Nothing

    End Function

answered Jan 26, 2020 at 14:11

Zer0Kelvin's user avatar

Zer0KelvinZer0Kelvin

3142 silver badges7 bronze badges

1

Return to VBA Code Examples

This code will check if an Office App is Running. If the App is not running then it opens the App.

Check if Microsoft Word Application is Open

Sub Check_If_App_Is_Open()

'Check if Microsoft Word is Running
wApp = "Word.Application"

If IsAppRunning(wApp) = True Then
 MsgBox "Word is Running"
Else
 MsgBox "Word is Not Running"
 'Create a new instance
 Set oApp = CreateObject(, wApp)
End If

End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

alt text

Learn More!

<<Return to VBA Examples

vba-free-addin

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

(No installation required!)

Free Download

I have a Winforms application that launches Word to automate and edit documents. I would like the code to work.

I would like to check if Word (WINWORD.EX) is already running.

if Word is running then

use the existing session of Word

Else

Create a new instance of Word

End if

Im using the following code

The results are

If Word is running

Returns true and the code continues

If Word is not running

An exception error displays

Operation unavailable (Exception from HRESULT:0x800401E3 (MK_E_UNAVAILABLE))

In the function IsWordRunning

On line 

Dim wordObj As Object = Marshal.GetActiveObject("Word.Application")

Code is…

Dim objWordApp As Word.Application

‘ check if Word running
If IsWordRunning() = True Then

   MsgBox("Winword.exe is running")

   objWordApp = CType(Marshal.GetActiveObject("Word.Application"), Word.Application)

Else

    MsgBox("Winword.exe NOT running")

    objWordApp = New Microsoft.Office.Interop.Word.Application

End If



Public Function IsWordRunning() As Boolean
   Dim wordObj As Object = Marshal.GetActiveObject("Word.Application")
   Return Not wordObj Is Nothing
End Function

we have an application that runs MS Word (hidden) to print documents.

If one of the printers has a problem, then Word hangs while waiting for the spooler to return the ‘queued’ message.

We have found that if we make Word visible (by using VBA in Excel with GetObject andoWordApp.visible=true for
example) then the process continues printing the other documents with no problem.

We would like to make this more automatic by having a VBScript check for Word in running processes, if it finds it, make it visible, wait for a few seconds, hide it, and quit…

But I have a problem that the VBScript GetObject function
instantiates Word if it’s not already running.

how should I check that word is running using VBScript without creating an instance of it?

here is the code I have in my VBScript file:

dim oWord, WScriptShell

set oWord = getobject("", "Word.Application")
set WScriptShell = CreateObject("WScript.Shell")

if isobject(oWord)  then 'and oWord.Documents.count>0
    wscript.echo("Word is running")
    oWord.visible=true
    WScript.Sleep 1000
    oWord.visible=false
else
    wscript.echo("Word not running")
end if

so what should I use to check if word is running without creating an instance of it?

  • Edited by

    Friday, February 21, 2014 11:45 AM

  • Home
  • VBForums
  • Visual Basic
  • Visual Basic 6 and Earlier
  • Determine if WinWord.Exe is running

  1. Jan 7th, 2015, 01:16 PM


    #1

    PIreland is offline

    Thread Starter


    New Member


    Question Determine if WinWord.Exe is running

    Hello,
    Newbee here and somewhat inexperienced with VBScript so here goes…

    I have a need to make sure that there aren’t any word applications running when I run a script. Sometimes, Word will not have a file open but it will be there in the taskbar (application is running but no file). Therefore, I need to kill this word application so I can open one with the script.

    Guy Thomas was kind enough to provide this sub-routine to kill the running processes. It works quite well.

    But, in my script, I’m posting a message box that notifies the user that the system is going to close all Word applications. This requires and OK or Cancel response from the user.

    I’d like to prevent this message from popping-up if there aren’t any word processes running. My problem is that I don’t know how to determine that there is at least one instance running. If I can do that, then I can put an IF statement and control when the user prompt pops up.

    So, how would I illicit a response from the system as to whether or not there are any WinWord.Exe processes running?

    Public Sub Word_Grim_Reaper()
    ‘ ProcessKillLocal.vbs
    ‘ Sample VBScript to kill a program
    ‘ Author Guy Thomas http://computerperformance.co.uk/
    ‘ Version 2.7 — December 2010
    ‘ ———————— ——————————-‘

    Dim objWMIService, objProcess, colProcess
    Dim strComputer, strProcessKill
    strComputer = «.»
    strProcessKill = «‘WinWord.Exe'»

    Set objWMIService = GetObject(«winmgmts:» _
    & «{impersonationLevel=impersonate}!\» _
    & strComputer & «rootcimv2»)

    Set colProcess = objWMIService.ExecQuery _
    («Select * from Win32_Process Where Name = » & strProcessKill )
    For Each objProcess in colProcess
    objProcess.Terminate()
    Next

    End Sub

    Thank you


  2. Jan 7th, 2015, 02:01 PM


    #2

    Re: Determine if WinWord.Exe is running

    Hey,

    VScript <> VB6

    Regardless, if you just need a script to close a task just Shell window’s taskkill command line.
    e.g close notepad.exe on a local machine

    Code:

    taskkill /im notepad.exe

    for more info and parameters: http://technet.microsoft.com/en-us/l…/bb491009.aspx

    a small search to figure out if a process is running via VB, got me to this thread:
    http://www.vbforums.com/showthread.p…unning-Process
    you cna find at least 3 different ways to do so in that thread alone.


  3. Jan 7th, 2015, 02:05 PM


    #3

    Re: Determine if WinWord.Exe is running

    I think you mean elicit not «illicit» above.

    Not only isn’t this a scripter’s forum, what you are trying to do is frought with woes. Office applications are not meant to be run unattended from any script, service, etc. See Considerations for server-side Automation of Office which also applies to any kind of batch activity such as a scheduled task.


  4. Jan 7th, 2015, 02:19 PM


    #4

    PIreland is offline

    Thread Starter


    New Member


    Re: Determine if WinWord.Exe is running

    Yes, elicit is the word I was looking for, thank you.

    I’m sorry about the misuse of the VB Forum. For some reason, I assumed that VB and VB Script were so closely related that I could get some help on this forum for the problems I’m experiencing. I came across this forum because of other posts that dealt with problems similar to mine. Apparently, I can get some help.

    Stum, the link you found matches what I was looking for and it even looks like VnTalk (the creator of that thread) has the same code that I’m using.

    I think the code:

    If colProcesses.Count Then
    isRunning = True
    Else
    isRunning = False
    End If

    Thank you!

    Quote Originally Posted by stum
    View Post


  5. Jan 9th, 2015, 05:20 AM


    #5

    Re: Determine if WinWord.Exe is running

    For future searches, if anyone still needs to enumerate through running processes and find out if one process is currently running:

    Code:

    Dim Process As Object
    For Each Process In GetObject("winmgmts:").ExecQuery("Select * from Win32_Process")
        If Process.Caption = "WINWORD.EXE" Then
            Msgbox ("Word is Running !")
        End If
    Next

    credit on this snippet goes to dee-u *


  6. Jan 9th, 2015, 01:08 PM


    #6

    Re: Determine if WinWord.Exe is running

    VBScript:

    Code:

    msgbox wordIsRunning
    
    function wordIsRunning
        dim wdApp
        on error resume next
        set wdApp = GetObject(, "Word.Application")
        wordIsRunning = (err.Number = 0)
        set wdApp = nothing
    end function


  • Home
  • VBForums
  • Visual Basic
  • Visual Basic 6 and Earlier
  • Determine if WinWord.Exe is running


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

Norton


  • #1

Hi All,

I have a COM+ application which will get data from database and then export
as word file.

eg.
Set oWordApp = CreateObject(«Word.Application»)
oWordApp.Documents.Open Filename:=DocumentPath, ReadOnly:=False

For every COM+ operation, the program will create a word instance and then
write data, and the performance is poor.
Is there any method in VB to detect if a Word Application is running, and
use that application instead of create a new one?

Thx all of you!

Regards,
Norotn

Advertisements

Richard Myers


Want to reply to this thread or ask your own question?

You’ll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.


Ask a Question

Using MS Access 2003. I open a Word document, but need to know how to determine if MS Word is closed before closing a MS Access form. The Word application object is ‘wo’. I get the run-time error as mentioned below.

Private Sub cmdbCloseCC_Click()
On Error GoTo PROC_ERR
    Dim wn As String
    wn = «Word.Application»
    If Me.IsAppRunning(wn) = True Then
        wo.Quit
        Set wo = Nothing
    End If

   
    DoCmd.Close acForm, «frmCC_Status»
    Application.Quit
PROC_EXIT:
    Exit Sub
PROC_ERR:
    MsgBox Err.Description
    Resume PROC_EXIT
End Sub
___________________________________________

Function IsAppRunning(ByVal appName) As Boolean
    Dim oApp As Object
    On Error Resume Next

   
    Set oApp = GetObject(, appName) ‘Error here — Run-time error ‘429’: ActiveX component can’t create object
    Debug.Print oApp
    If Not oApp Is Nothing Then
        Set oApp = Nothing
        IsAppRunning = True
    End If
End Function

Similar topics

6

Detect power redirection to ups

by: Stephane Belzile |
last post by:

Is there a way I can detect in vb.Net the power has switched to a UPS
unit in case of power failure?

Thanks

.NET Framework

6

How to detect when the external programm closes the file?

by: Ana |
last post by:

Hi!
I have problems with the following scenario:
My application is developed using C# under .NET. It must run on all Windows
versions starting…

C# / C Sharp

7

Creating microsoft word document using C#.net

by: Zeke |
last post by:

I’m using the following code to create word document but the problem is if
you go to task manager you’ll see a WINWORD.EXE process is running but…

C# / C Sharp

6

Detect power redirection to ups

by: Stephane Belzile |
last post by:

Is there a way I can detect in vb.Net the power has switched to a UPS
unit in case of power failure?

Thanks

.NET Framework

1

What Makes Product Development Lean?

by: beacampos |
last post by:

Constantly decreasing costs, no waste, minimum throughput time, maximum capacity, unlimited flexibility, and high customer satisfaction. Sounds too…

Software Development

0

AntDB�s latest achievement at Global Distributed Cloud Conference to drive deeper digital transformation of enterprises

by: antdb |
last post by:

On August 26, the Global Distributed Cloud Conference was held in Beijing, which was dedicated to promoting the development of distributed cloud…

General

0

How PDDON’s online drawing surprised you?

by: pddon |
last post by:

1. Brief introduction
PDDON is a free online drawing tool that supports low code. It can be used to draw architecture diagram, flow diagram, UML,…

Web Applications

0

Creating a social network (help)

by: Saiars |
last post by:

Hello! I wish to assemble a team of enthusiasts with the help of which we will create a strong social network so that everything is as we want in it….

General

0

Forrester: Four Digital Intelligence Products of AsiaInfo Included in China Data Governance Ecology Report

by: antdb |
last post by:

Recently, Forrester, an internationally renowned ICT research and consulting organization, recently released the Trend Report: Navigate The Data…

General

1

MS Access Query Criteria

by: Computer0300 |
last post by:

If I type !! in my query criteria and query deals with its value which may be (Like «» & «Raj Poot» & «») Or (Like «» & «Malak» & «»). Is it…

Microsoft Access / VBA

4

SueHopson

Alternate colors in an Unbound Continuous Form

by: SueHopson |
last post by:

Hi Everyone,

All my research leads to http://www.lebans.com/alternatecolordetailsection.htm BUT it’s a .mdb file I can’t open so I’m not sure if…

Microsoft Access / VBA

0

Having a problem with the 0 not showing

by: CD Tom |
last post by:

Right now I have a field type short text. in that field I’m putting numbers .345 .432, etc. but when the number is .340 the zero doesn’t show up. …

General

3

SueHopson

Data Validation when using a Close button

by: SueHopson |
last post by:

Ok, I have spent way too much time on this, so reaching out for guidance.

When I run the code below it does everything I need it to do, except…

Microsoft Access / VBA

Like this post? Please share to your friends:
  • Word application format text
  • Word application for windows
  • Word application for ipads
  • Word application find text
  • Word application documents add