VB.net Word没有关闭

时间:2015-04-11 03:21:21

标签: vb.net ms-word

当用户点击按钮时,它会打开Word文档。用户关闭文档后,Word仍在后台运行(由任务管理器确认)。有没有办法清除Word中的内存?

这就是我的代码电流:

 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 

4 个答案:

答案 0 :(得分:1)

您需要正确关闭Com对象,在调用.Quit后需要Marshall类来执行此操作。检查Task Manager,您会看到它消失了。同样适用于Excel

Marshal.FinalReleaseComObject(appWord)

答案 1 :(得分:0)

您可以将Dim appWord As New Word.Application移到子网之外,然后稍后再从其他子网中调用appWord.Quit()

答案 2 :(得分:0)

试试这个。

外部方法块:

Private appWord As Word.Application
Private docWord As Word.Document

在您的事件处理程序中:

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

FormClosing事件处理程序或其他任何地方:

Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) _
Handles MyBase.FormClosing

    Me.appWord.Quit()

End Sub

答案 3 :(得分:0)

我有类似的问题,解决方案是双重的。首先,我使用自己的等效appWord.Quit()来终止程序。请注意,除非您希望提示最终用户是否保存更改,否则您需要提供.Quit方法的参数。像这样:appWord.Quit(Word.WdSaveOptions.wdDoNotSaveChanges)

其次,我在网上发现了一个方便的小Sub,用于完全释放任何Word或Excel自动化对象并对其进行修改以满足我的需要。

尝试在appWord.Quit(Word.WdSaveOptions.wdDoNotSaveChanges)之后调用此Sub:

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

此子循环以确保所有实例和对象完全关闭并从内存中删除。

希望有所帮助!