Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Terminating a Word process from Excel VBA

Status
Not open for further replies.

ging18

Programmer
Mar 25, 2009
14
GB
Hello All

I need to stop a Word process using an Excel macro.

Excel will create an instance of Word, use it and then close word. This works the majority of the time. When it does not work the Word process is still running in the background and needs to be stopped using task manager.

What I’m after is a way to terminate the instance of word created by excel.

I have found how to terminate all word instances but cannot workout how to close the one opened by the macro.

The terminate method will close a specific process ID but I cannot find a way of identifying the process ID of the instance of word created.

Does anyone have any idea how to Kill a specific Word process?

Any help or ideas will be greatly appreciated as this issue has about defeated my knowledge….

Thank you kindly
Christian
 
Going the other way, I have a Word macro that opens and closes an Excel instance. In the process of opening, I create an object reference:
Set xlApp = CreateObject("Excel.Application")
Later I destroy that specific object:
xlApp.Quit

Wouldn't the same apply here?
Code:
wdApp=createobject("Word.Application")
...
wdApp.quit

_________________
Bob Rashkin
 
Thanks for you response.

Normally that does work fine.

The problem is, while I have the word file open the contents of other word files are copied and pasted into the new document. If one of the source files is corrupted the paste operation (or file insert method) causes word to crash. After the crash I can no longer access the word instance so I cannot close it using the normal methods.

So far the only way i can think of is to use task manager to kill the process.

What I'm currently working on is a method to validate the source file is ok when it is selected. To do this i am attempting to copy and paste the file. If it works the file is processed, if it fails the method tells the user to check their document. I am now trying to clean up the open word processes when a file fails.
 



If one of the source files is corrupted ...

That is what you have to find a way to trap.

Skip,
[sup][glasses]Don't let the Diatribe...
talk you to death![tongue][/sup][sub]
[glasses]Just traded in my old subtlety...
for a NUANCE![tongue][/sub]
 
I think that is what i'm trying to do.

As Word only crashes when the contents of the document is pasted into another document the user generally does not know that there is a problem with their document.

From investigating the problem it seems to be caused by frequent changes to formatting and styles, page and section breaks or tables within the document.

All these appear to work fine in the source document but the corrupted source document structure cannot be copied to a new book, this causes the crash.

That lead me to writing the function to check the document is ok before the main macro for combining documents is executed. So far the function can identify when a document is corrupt but i cannot close word after a corrupt document is found.

 
You should be trying to identify, and eliminate, what causes corruption and/or crashes - neither is normal and one would not expect to have to cater for either in VBA code.

Enjoy,
Tony

------------------------------------------------------------------------------------
We want to help you; help us to do it by reading this: Before you ask a question.

I'm working (slowly) on my own website
 
I agree. While true, you do have an issue with the effects of your crashed instance of Word, the real issue (IMO) is the fact you appears to have so many corrupt files.

Further, since you state that it seems to be OK in the source doc, but corrupt if copied - which I must admit I find questionable - there may in fact be a way to get your contents without an actual Copy/Paste operation.

You do not state exactly how you are doing your copy, but are you actually using a .Copy instruction? It may be possible to use range objects and Set them, thus avoiding use of Copy and Paste.

Lastly, is this a many iteration action? Are you do LOTS of copying? That itself can cause some wonky things to happen.

Gerry
 
Hi Christian,

You previously posted this question in:
where I answered you in terms similar to what you're now being advised above.

It's rude to post the same question in multiple forums and not let on - especially when you don't acknowledge the advice you've already received.

[MS MVP - Word]
 
Thanks everyone for their responses.

Macropod, I'm sorry if I have offended with the multiple posts. I was just trying to capture as wide an audience as possible. In future I will only be using this site as it’s the only one my works network will allow me to log into. The details you posted on the other forum are correct and work exactly as required, until a corrupted word file is used.

On the word documents. I agree that the users should not be creating corrupt files and it amazes me how many I have been exposed to since starting this project. From my understanding the corruptions are caused by a combination of styles, section/page breaks and tables. The documents always start healthy but after a multiple updates to formatting problems occur.

I have examples of two types of corruption. In some when you open the file it shows a message “File corrupted” but clicking ok allows normal use of the file. The second type I’ve seen is where the file opens and can be used as normal. It allows full use of all features and copy pasting within the document. However as soon as you try and copy/paste to a different document it crashes out.

The first type seems to occur on large documents 200 plus pages. These are unlikely to be used by the tool but should still be handled correctly.

My understanding of the second type is that the structure of the source document has as developed over time, as changes are made part of the structure are lost. When pasting into a new document the lost structure cannot be duplicated so it falls over. Almost like driving from A to B with out recording the directions. You can happily get to C but cant tell somebody else how too because you cannot remember how you got to B.

The method I’m using for copy and pasting is actually calling the method used by the “Insert>File” menu option (InsertFile filename). I have also tried the Content.Copy, then Selection.paste method. Both methods experience the problem.

I would expect this process to only be executed for 2 or 3 files per operation under normal usage. However there is nothing to stop user attaching any number of files that they may require and there are plans to fully automate the process which would result in potentially 100ish files being processed in one execution.

I think that “fixing” the word files is unlikely so I have gone for testing the files when they are inputted. If there is a problem the details are explained to the user who can then fix it themselves and supply a working file. This might not be the most user friendly solution but its their own fault for not being able to use word properly.

The code I have used to make this check is attached.

------------------
Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As Any, ByVal lpWindowName As String) As Long

Public Declare Function GetWindowThreadProcessId Lib "user32" _
(ByVal hwnd As Long, lpdwProcessId As Long) As Long


' Check to see if data can be copied and pasted from a word file.
'-------------------------------------
' pstrPath File path
'-------------------------------------
' Returns True if the file is corrupt
' False if the file is ok
'-------------------------------------

Public Function fblnIsFileCorruptForCopyAndPaste(ByVal pstrPath As String) As Boolean

Const METHOD_NAME = "fblnIsFileCorruptForCopyAndPaste"

On Error GoTo Error

Dim wrdFile As Word.Document ' The word document
Dim wrdMain As Word.Document ' The file being created
Dim wrdMApp As Word.Application
Dim strName As String
Dim lHwnd As Long
Dim lProcessID As Long

' If the file is a word document, preview it...
If Right(pstrPath, Len(pstrPath) - InStrRev(pstrPath, ".") + 1) = ".doc" Then

Set wrdMApp = CreateObject("Word.Application")

' Add the preview
Set wrdFile = wrdMApp.Documents.Open(Filename:=pstrPath, ReadOnly:=True, Visible:=False)
Set wrdMain = wrdMApp.Documents.Add(Visible:=False)

wrdFile.Content.Copy

' Try pasting the data. If there is a problem
' it will fail here.
wrdMain.Select
wrdMApp.Selection.Paste

wrdFile.Close False
wrdMApp.Quit False

Set wrdFile = Nothing
Set wrdMain = Nothing
Set wrdMApp = Nothing

fblnIsFileCorruptForCopyAndPaste = False
Else
' Not a word file so corrupt
fblnIsFileCorruptForCopyAndPaste = True
End If

Exit Function

Error:

' Has a paste error occured?
If Err.Number = -2147417851 Then

' Set the return value
fblnIsFileCorruptForCopyAndPaste = True

' Close the temp target word file
wrdMain.Select
wrdMain.Close False

' Find the handle of the word application
lHwnd = FindWindow(vbNullString, wrdFile.Name & " (Read-Only) - " & wrdMApp.Caption)
If lHwnd = 0 Then
lHwnd = FindWindow(vbNullString, wrdFile.Name & " - " & wrdMApp.Caption)
End If

' Use the handle to get the ProcessId. This is returned "ByRef"
GetWindowThreadProcessId lHwnd, lProcessID

' Terminate the Process
TerminateProcess lProcessID

Exit Function
Else
' Its a general error, process as normal
' handle Error
End If

End Function


' Closes the process passed to the method
' Modified from example on
' '-------------------------------------
' pstrPath File path
'-------------------------------------
' Returns True if a process was terminated
'-------------------------------------
Public Function TerminateProcess(ByVal plngPID As Long) As Boolean

Const METHOD_NAME = "TerminateProcess"

On Error GoTo Error

'---------------------------------------------------------------------------------------
' : Terminates a process. First checking to see if it is running or not.
' : Uses WMI (Windows Management Instrumentation) to query all running processes
' : then terminates ALL instances of the specified process
' : held in the variable strTerminateThis.
' :
' : ***WARNING: This will terminate a specified running process,use with caution!.
' : ***Terminating certain processes can effect the running of Windows and/or
' : ***running applications.
'---------------------------------------------------------------------------------------

Dim strTerminateThis As String ' The variable to hold the process to terminate
Dim objWMIcimv2 As Object ' CIMV2 Namespace
Dim objProcess As Object
Dim objList As Object
Dim intError As Integer
Dim intX As Integer

' Process to terminate,
strTerminateThis = "WINWORD.EXE"

' Connect to CIMV2 Namespace
Set objWMIcimv2 = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")

' Find the process to terminate
Set objList = objWMIcimv2.ExecQuery _
("select * from win32_process where name='" & strTerminateThis & "'")

' Set the return value to false, nothing terminated
TerminateProcess = False

' Check to see if any process were found, if not then the app isnt running
' and there is nothing to close
If objList.Count > 0 Then 'If 0 then process isn't running

' Find the matching process from the list of running process
For Each objProcess In objList

' Check the process ids match
If objProcess.processID = plngPID Then
intError = objProcess.terminate 'Terminates a process and all of its threads.

If intError = 0 Then
TerminateProcess = True
End If
Exit For
End If
Next

End If

Set objWMIcimv2 = Nothing
Set objList = Nothing
Set objProcess = Nothing

Exit Function

Error:
' Handle Error
End Function

------------------------------

The points that may be worth noting are the two API calls, FindWindow and GetWindowThreadProcessID.

FindWindow caused much trouble, as I could not get the right combination of inputs to identify the correct window. Once the correct string had been created everything started to drop into place. FindWindow returns the window handle, this is used by GetWindowThreadProcessID to get the PID.

With the PID details the TerminateProcess example code could be easily be modified to only kill the required process.

I’m hoping that this work around will solve the issue.

I would again like to thank you all for your help.

Thanks
Christian
 
Please use the TGML code tags when posting code. Thanks.

"This might not be the most user friendly solution but its their own fault for not being able to use word properly."

Amen to that. The fact that there appears to be much manual formatting is indeed the users "fault". Frankly, this comes down to a training issue, which - sadly - I expect will not be resolved. I have been trying for 15 years to get people in our organization to use Word even moderately properly. I have failed, as I doubt more than 5% have even the remotest clue, despite my rantings, or the in-houses courses I deliver.

So, your corrupt files are a problem. InsertFile will, as you have found, not handle it.

" I have also tried the Content.Copy, then Selection.paste method. Both methods experience the problem."

Which is why I suggested trying to use another method that does not use copy and paste.

Good luck.

Gerry
 
This might not be the most user friendly solution but its their own fault for not being able to use word properly.
Pesky users! We'd all be better off without them, eh?

I'm afraid I disagree.

I can appreciate that you may have been placed in a difficult position and that you may be making the best you can of a bad job, but ..

Not being able to use Word properly, when doing so is part of their job is not really the individual user's fault. It is the employer's fault and it seems somewhat unjust to pile more misery onto the user because of it.

If they get in a mess by failing to use the product 'properly', whether due to a lack of training or not, it is still wrong that it leads to corruption of documents. If it happens routinely, my personal view is that Microsoft should be told/consulted. Whether or not they will listen is another question, but they should; it is not in their interest for this to happen.

Enjoy,
Tony

------------------------------------------------------------------------------------
We want to help you; help us to do it by reading this: Before you ask a question.

I'm working (slowly) on my own website
 
Well I agree with THAT. If a customer has massive and consistent corruption of files because of poor usage by the users, it is NOT totally the users fault. Good software simply should not be that easily corrupted.

I agree, to an extent, it IS the employer responsibility to get users adequate training. However, speaking from personal experience, I have given a huge amount of Word training, and sometimes it makes no difference at all. Information on how to use Word well, including specifics on the documents our users...ummm...use, is readily available on our intranet. Custom Help has been made to assist them. They still do not use Word even moderately well.

Nevertheless, I DO agree that if you have a massive corruption issue, Microsoft should be informed.

Gerry
 
I do agree that it is not really the users fault for not knowing how to use Word. Although training is available within our company for it and all the other office packages I’m fairly sure I’m one of few that have actually completed them. Most people just seem to manage on what they pick up as they go along.

I’ve been looking a bit more at the documents that corrupt. All the examples I’ve got have the same source. The person in question has been trained and would consider himself an “Expert”. He also creates documents that are vastly over styled.

In my organisation we’re using Word/Excel 2000. I have now tried the same documents on Word 2003 and in some instances they hang a bit, but none of them crash Word. I’ve also found that one of the worst offenders had a massive amount of unaccepted tracked changes, where I was copying a 1 page example there was actually a good 60 page document. So I guess I’m not as clued up as I thought or I’d have checked Tracking Changes on my work machine (accepting the changes still crashes word).

I’m hoping that once the new tool goes live the problem will disappear as when trained the users will be told that there is no need to apply extensive formatting to the documents they attach, as the tool will be reformatting the documents to the required output automatically. All they need to do is enter their details in the document.

They will still have the option to attached the older potentially corrupt files, but I’m fairly sure that I’ll be the first person dialled when a file gets rejected so I’ll have the opportunity to monitor just how many corrupt files exist.

If it is a wide spread problem amongst the general population then I’ll bat it over to the big boys.

Thanks again for all you help.

 
Well done for all the investigation. I have to say that you will not find much support available for Word 2000 these days, when even 2002 is out of support.

60 pages of tracked changes in a 1-page document, from someone without the nous to tidy it up before submitting it to anyone else, suggests a mind even more disorganised than mine, and an employee of little value.

Enjoy,
Tony

------------------------------------------------------------------------------------
We want to help you; help us to do it by reading this: Before you ask a question.

I'm working (slowly) on my own website
 
Hi ging18,

Perhaps a simple expedient when trying to process a document with outstanding tracked changes is to not process it - which you could argue for on the basis that, until the changes have been accepted/rejected, you can't be sure your processing the final version of the document. You can easily test with with code along the lines of:
Code:
ActiveDocument.Revisions.Count
The other thing to watch for, if you're not doing so already and you're writing to another document, is that its track-changes setting should temporarily be forced to 'off'. You could do this with code along the lines of:
Code:
Dim TrkStatus As Boolean      ' Track Changes flag
With ActiveDocument
  TrkStatus = .TrackRevisions
  .TrackRevisions = False
  ... all your processing
  .TrackRevisions = TrkStatus
End With
Cheers

[MS MVP - Word]
 
I was assuming that the users would only be working with finalised documents, but as seen with my sample data this may not be the case. So it does make sense to block all documents with unprocessed tracked changes.

I’ve add added the checks to reject documents that contain tracked changes and as suggested turned off Track Changes when creating the output document.

Thanks for the help.

Christian
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top