VB.NET操作Word,解决“RPC 服务器不能用”错误

环境:vb.net 2005,Word2003

需求:A、用vb.net打开word,从自定义的模板生成WORD文档。

B、把相应字段替换成用户指定的数据。

C、文档关闭前,自动读取户修改后固定位置的文本到vb.net中。

D、不管用户是否选择保存Word文档,都自动取得需要的文本。

E、用户可以通过vb.net关闭Word,也可以手工关闭Word

 

1)选择vb.net项目,右键属性=》添加引用=COM,添加Microsoft Word 11.0 Object Library。在程序中引用方法:Imports Microsoft.Office.Interop

2MyWord_Quit是关键,如果不在这里面释放掉用Dim WithEvents定义的MyWord,当用户不在Vb.net中,而用手工直接关闭Word程序后,再次调用Word程序,就会产生RPC 服务器不能用”错误。

3)程序代码:

Imports Microsoft.Office.Interop

Public Class Form1

    Dim WithEvents MyWord As Word.Application   'WithEvents        '用于存放   Microsoft   Word   引用的变量。  

    Dim MyDoc As Word.Document

 

    Dim WordWasNotRunning As Boolean

    Dim DocWasNotOpened As Boolean

    Dim str1 As String

'-------------------------------------------------------------------------------------

    '打开Word程序,如果Word已经运行,就GetObject,否则就CreateObject

    Private Sub Get_Word()

        On Error GoTo Open_word       '不带第一个参数调用   Getobject   函数将  

        '返回对该应用程序的实例的引用,如果该应用程序不在运行,则会产生错误。  

        MyWord = GetObject(, "Word.Application")

        GoTo Set_Visible

Open_word:

        MyWord = CreateObject("Word.Application")

        '如果发生错误则要创建一个Word.Application对象  

        WordWasNotRunning = True   '表明Word是由程序启动的,最后应该关闭  

        Err.Clear()

Set_Visible:

        MyWord.Visible = True

        MyWord.Activate()

    End Sub

'-------------------------------------------------------------------------------------

    '从模板生成Word文档

    Public Sub NewDocWithModel(ByVal FileName As String)

        Dim missing = System.Reflection.Missing.Value

        Dim isVisible As Boolean = False

        Dim strName As String

 

        strName = FileName

        MyDoc = MyWord.Documents.Add(strName, missing, missing, isVisible)

        DocWasNotOpened = True

        MyDoc.Activate()

        MyWord.Visible = True

    End Sub

'-------------------------------------------------------------------------------------

    Private Sub Get_Doc()

        Dim MyTime As String

     

        MyTime = Format(Now, "yyyyMdhm")

 

        '在此处对文件进行操作。 

        MyDoc.Activate()

        MyDoc.Select()

        With MyWord.Selection.Find

            .ClearFormatting()

'替换Word文档模板中的“<姓名><性别>”为相应值

'<姓名>是提前在模板是定义的,也可以用别的比较特别的字符代替

            While .Execute("<姓名>")   '被替换的内容  

                MyWord.Selection.TypeText(Text:="张三")   '替换后的内容  

            End While

            While .Execute("<性别>")   '被替换的内容  

                MyWord.Selection.TypeText(Text:="")   '替换后的内容  

            End While      

        End With

    End Sub

'-------------------------------------------------------------------------------------

    '打开Word,从模板生成Word文档,替换文本

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Get_Word() '打开Word程序

        NewDocWithModel("D:/bai/vb.net/内部明电批办单.dot") '从模板生成文档

        Get_Doc() '替换相关文本

    End Sub

'-------------------------------------------------------------------------------------

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

        MsgBox("WordWasNotrunning=" & WordWasNotRunning & ";DocWasNotOpened=" & DocWasNotOpened)

 

        If WordWasNotRunning Then 'Wordvb.net打开的,关闭它。

            WordWasNotRunning = False

            DocWasNotOpened = False

            MyDoc.Close(Word.WdSaveOptions.wdDoNotSaveChanges)

            MyWord.Quit()

        Else 'Word以前就打开,只关闭vb.net打开的Word文档

            If DocWasNotOpened = True Then

                DocWasNotOpened = False

                MyDoc.Close(Word.WdSaveOptions.wdDoNotSaveChanges) '(Word.WdSaveOptions.wdDoNotSaveChanges)

            End If

        End If

        '释放对象

        MyDoc = Nothing

        MyWord = Nothing

    End Sub

'-------------------------------------------------------------------------------------

    '显示从Word中取得的数据

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click

        TextBox1.Text = str1

    End Sub

'-------------------------------------------------------------------------------------

    '关闭前保存数据到变量

    Private Sub MyWord_DocumentBeforeClose(ByVal Doc As Microsoft.Office.Interop.Word.Document, ByRef Cancel As Boolean) Handles MyWord.DocumentBeforeClose

        '保存Word文档中,表格1的第3行第2列的文本,以后Vb.net调用

        str1 = Doc.Tables(1).Rows(3).Cells(2).Range.Text

    End Sub

'-------------------------------------------------------------------------------------

    'Word退出后,执行的操作

    '如果用户手工关闭Word,那么必须释放MyDocMyWd,否则再次打开Word就会出错

    Private Sub MyWord_Quit() Handles MyWord.Quit

        MyDoc = Nothing

        MyWord = Nothing

        WordWasNotRunning = False

        DocWasNotOpened = False

    End Sub

End Class

 

你可能感兴趣的:(vb.net)