关闭 Word 应用程序,vb.net

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18712753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 15:01:12  来源:igfitidea点击:

Closing Word app, vb.net

vb.netms-word

提问by TeeJay

i am trying to search within word documents, using vb.net it worked but i cant seem to close the files after searching them, here is the code i use how to close the word apps after being searched ?

我正在尝试在 word 文档中搜索,使用 vb.net 它工作但我似乎无法在搜索后关闭文件,这是我使用的代码如何在搜索后关闭 word 应用程序?

Dim oWord As Word.Application = Nothing
    Dim oDocs As Word.Documents = Nothing
    Dim oDoc As Word.Document = Nothing
    Dim folderDlg As New FolderBrowserDialog
    folderDlg.ShowNewFolderButton = True
    If (folderDlg.ShowDialog() = DialogResult.OK) Then
        Dim root As Environment.SpecialFolder = folderDlg.RootFolder
    End If
    Dim l_Dir As IO.DirectoryInfo
    Dim fldpath As String = folderDlg.SelectedPath
    If IO.Directory.Exists(fldpath) Then
        l_Dir = New IO.DirectoryInfo(fldpath)

        For Each l_File In Directory.GetFiles(fldpath, "*.docx")


            Dim searchFor As String = TextBox1.Text


            oWord = New Word.Application()
            oWord.Visible = False

            oDocs = oWord.Documents
            oDoc = oDocs.Open(l_File, False)
            oDoc.Content.Find.ClearFormatting()

            Dim findText As String = searchFor

            Try
                If oDoc.Content.Find.Execute(findText) = True Then
                    MessageBox.Show("OK.")

                    oWord.NormalTemplate.Saved = True
                    oWord.ActiveDocument.Close(False)
                    oDoc.Close()
                    oWord.Quit()

                    If Not oDoc Is Nothing Then
                        Marshal.FinalReleaseComObject(oDoc)
                        oDoc = Nothing
                    End If
                    If Not oDocs Is Nothing Then
                        Marshal.FinalReleaseComObject(oDocs)
                        oDocs = Nothing
                    End If
                    If Not oWord Is Nothing Then
                        Marshal.FinalReleaseComObject(oWord)
                        oWord = Nothing
                    End If

                Else
                    MessageBox.Show("No.")
                End If

            Catch ex As Exception

            End Try
            ComboBox1.Items.Add(l_File)
        Next

    End If

回答by varocarbas

First thing you should bear in mind is that "releasing the objects" in Word is not as difficult as in Excel and thus you are (unnecessarily) over-complicating things. In any case, you should intend to not over-declare variables (what is the exact point of oDocs?). And, lastly, you should always perform a step-by-step execution when things go wrong to find out what might be happening (you are applying your "objects release" only for "OK" cases, not in any situation: when the result is "No", the objects would have to be released too).

您应该记住的第一件事是,在 Word 中“释放对象”不像在 Excel 中那么困难,因此您(不必要地)使事情变得过于复杂。在任何情况下,您都不应过度声明变量(确切的点是oDocs什么?)。最后,当出现问题时,您应该始终执行逐步执行以找出可能发生的情况(您仅在“正常”情况下应用“对象释放”,而不是在任何情况下:当结果是“否”,对象也必须被释放)。

Here you have a corrected code accounting for all the aforementioned issues:

在这里,您有一个更正的代码,可以解决上述所有问题:

Dim oWord As Word.Application = Nothing
Dim oDoc As Word.Document = Nothing
Dim folderDlg As New FolderBrowserDialog
folderDlg.ShowNewFolderButton = True
If (folderDlg.ShowDialog() = DialogResult.OK) Then
    Dim root As Environment.SpecialFolder = folderDlg.RootFolder
End If
Dim l_Dir As IO.DirectoryInfo
Dim fldpath As String = folderDlg.SelectedPath
If IO.Directory.Exists(fldpath) Then
    l_Dir = New IO.DirectoryInfo(fldpath)

    For Each l_File In Directory.GetFiles(fldpath, "*.docx")

        Dim searchFor As String = TextBox1.Text

        oWord = New Word.Application()
        oWord.Visible = False

        Try
            oDoc = oWord.Documents.Open(l_File, False)
            oDoc.Content.Find.ClearFormatting()

            Dim findText As String = searchFor

            Try
                If oDoc.Content.Find.Execute(findText) = True Then
                    MessageBox.Show("OK.")

                Else
                    MessageBox.Show("No.")
                End If

            Catch ex As Exception

            End Try

            oWord.NormalTemplate.Saved = True

            ComboBox1.Items.Add(l_File)
        Catch ex As Exception

        End Try

        oDoc = Nothing
        oWord.Quit()
        oWord = Nothing

    Next

End If

NOTE: note that, when iterating through all the Word files in a folder (and, in general, ones from any MS Office program), you can find temporary copies (starting with "~$...") which might trigger an error when being opened (and thus not allow the object-releasing part to come into picture); also, in general, when opening files something might go wrong; this is what explains the new try...catch I added and why I put the releasing part after it.

注意:请注意,在遍历文件夹中的所有 Word 文件(通常是来自任何 MS Office 程序的文件)时,您可以找到可能会触发错误的临时副本(以“~$...”开头)当被打开时(因此不允许物体释放部分出现);此外,一般来说,打开文件时可能会出错;这就是我添加的新 try...catch 以及为什么我将发布部分放在它之后的原因。

回答by ThomasFey

I don't know Vb.net, but in F# I used

我不知道 Vb.net,但在 F# 中我用过

System.Runtime.InteropServices.Marshal.ReleaseComObject xlApp |> ignore

after ".Quit()", to end the process, but you must search, how to give the name of your word application at the place of xlApp

在“.Quit()”之后,结束进程,但你必须搜索,如何在xlApp的位置给出你的单词应用程序的名称

I will place this after the "End If" at the end.

我将把它放在最后的“End If”之后。

I hope it will be helpfull for you

我希望它对你有帮助