Reputation: 33
When the user clicks on a button it opens a Word document. After the user closes the document, Word is still running in the background (confirmed by Task Manager). Is there a way to clear Word out of the memory?
This is what my code currents look like:
Private Sub UserDocumentationToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UserDocumentationToolStripMenuItem.Click
Dim appWord As New Word.Application
Dim docWord As New Word.Document
docWord = appWord.Documents.Open(Application.StartupPath & "\user_documentation1.docx", )
appWord.Visible = True
appWord.Activate()
End Sub
Upvotes: 1
Views: 1501
Reputation: 97
I had a similar problem and the solution was two-fold. First, I used my own equivalent of appWord.Quit()
to terminate the program. Note that unless you want the end user to be prompted whether to save changes, you will need to supply the parameter for the .Quit method. Like this: appWord.Quit(Word.WdSaveOptions.wdDoNotSaveChanges)
.
Second, I found a handy little Sub online for fully releasing any Word or Excel automation objects and modified it to suit my needs.
Try calling this Sub after appWord.Quit(Word.WdSaveOptions.wdDoNotSaveChanges)
:
Public Sub releaseObject(ByVal obj As Object)
Try
Dim CheckIt As Integer
CheckIt = System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
While CheckIt > 0
CheckIt = System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
End While
obj = Nothing
Catch ex As Exception
MsgBox(ex.Message)
Finally
GC.Collect()
GC.WaitForPendingFinalizers()
End Try
End Sub
This sub loops through to make sure all instances and objects are completely closed and removed from memory.
Hope that helps!
Upvotes: 0
Reputation: 20464
Try this.
Outside method blocks:
Private appWord As Word.Application
Private docWord As Word.Document
Inside your event handler:
Private Sub UserDocumentationToolStripMenuItem_Click(sender As Object, e As EventArgs) _
Handles UserDocumentationToolStripMenuItem.Click
Me.appWord = New Word.Application
Me.docWord = New Word.Document
Me.docWord = Me.appWord.Documents.Open(Application.StartupPath &
"\user_documentation1.docx", )
Me.appWord.Visible = True
Me.appWord.Activate()
End Sub
In your FormClosing
event handler or anywhere else:
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) _
Handles MyBase.FormClosing
Me.appWord.Quit()
End Sub
Upvotes: 0
Reputation: 9024
You need to close the Com
object correctly, after calling .Quit
you need the Marshall class to do that. Check Task Manager
and you will see it is gone. Same for Excel
as well.
Marshal.FinalReleaseComObject(appWord)
Upvotes: 1
Reputation: 776
You can move Dim appWord As New Word.Application
outside of the sub, and then call appWord.Quit()
from another sub at a later time.
Upvotes: 0