Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Open Word document using VB.NET
Message
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Environment versions
Environment:
VB.NET 1.1
OS:
Windows XP SP2
Database:
MS SQL Server
Miscellaneous
Thread ID:
00990971
Message ID:
00992701
Views:
44
Hi Cathi,

Much thanks for your assistance with the late binding - my solution now works on Word 97 and Word 2000 - as well as XP.

For anyone interested, I've modified an example I found at the MS site which used early binding. The code below shows how automating a Word mail merge can be done using late binding.

Just create a new VB.Net Windows application, add a command button and a multi-line text box (I used this to display error info as I was working on this) - then open the code window, and add this code.

(Important: Make sure to add OPTION STRICT OFF at the top of the code window)
 Private Sub InsertLines(ByVal LineNum As Integer, ByRef objSelection As Object)
        Dim iCount As Integer

        ' Insert "LineNum" blank lines.
        For iCount = 1 To LineNum
            objSelection.TypeParagraph()
        Next iCount
    End Sub


    Private Sub FillRow(ByVal Doc As Object, ByVal Row As Integer, _
    ByVal Text1 As String, ByVal Text2 As String, _
    ByVal Text3 As String, ByVal Text4 As String)

        With Doc.Tables.Item(1)
            ' Insert the data in the specific cell.
            .Cell(Row, 1).Range.InsertAfter(Text1)
            .Cell(Row, 2).Range.InsertAfter(Text2)
            .Cell(Row, 3).Range.InsertAfter(Text3)
            .Cell(Row, 4).Range.InsertAfter(Text4)
        End With
    End Sub


    Private Sub CreateMailMergeDataFile(ByRef objApp As Object, ByRef objDocs As Object, ByRef objDoc As Object, ByRef objMailMerge As Object)
        Dim wrdDataDoc As Object
        Dim iCount As Integer

        ' Create a data source at C:\DataDoc.doc containing the field data.
        objMailMerge.CreateDataSource(Name:="C:\DataDoc.doc", _
              HeaderRecord:="FirstName, LastName, Address, CityStateZip")
        ' Open the file to insert data.
        wrdDataDoc = objDocs.Open("C:\DataDoc.doc")
        For iCount = 1 To 2
            wrdDataDoc.Tables.Item(1).Rows.Add()
        Next iCount
        ' Fill in the data.
        FillRow(wrdDataDoc, 2, "Steve", "DeBroux", _
              "4567 Main Street", "Buffalo, NY  98052")
        FillRow(wrdDataDoc, 3, "Jan", "Miksovsky", _
              "1234 5th Street", "Charlotte, NC  98765")
        FillRow(wrdDataDoc, 4, "Brian", "Valentine", _
              "12348 78th Street  Apt. 214", "Lubbock, TX  25874")
        ' Save and close the file.
        wrdDataDoc.Save()
        wrdDataDoc.Close(False)
    End Sub


    Private Sub DoTheMerge()
        Dim objApp As Object
        Dim objDocs As Object
        Dim objDoc As Object
        Dim objDataDoc As Object

        Dim objSelection As Object
        Dim objMailMerge As Object
        Dim objMergeFields As Object
        Dim objDestination As Object
        'Dim objParagraph As Object
        'Dim objPara As Object
        Dim objRange As Object

        objApp = CreateObject("Word.Application")
        objApp.visible = True
        objDocs = objApp.Documents

        Try
            Dim StrToAdd As String
            ' Add a new document.
            objDoc = objDocs.Add()
            objDoc.Select()

            objSelection = objApp.Selection
            objRange = objSelection.range

            objMailMerge = objDoc.MailMerge
            objDestination = objMailMerge.Destination
            objMergeFields = objMailMerge.fields()

            objDoc.select()

            ' Create MailMerge Data file.
            CreateMailMergeDataFile(objApp, objDocs, objDoc, objMailMerge)

            ' Create a string and insert it in the document.
            StrToAdd = "State University" & vbCr & _
                        "Electrical Engineering Department"

            objSelection.ParagraphFormat.Alignment = _
                         Word.WdParagraphAlignment.wdAlignParagraphCenter

            objSelection.TypeText(StrToAdd)

            InsertLines(4, objSelection)

            ' Insert merge data.
            objSelection.ParagraphFormat.Alignment = _
                        Word.WdParagraphAlignment.wdAlignParagraphLeft


            objRange = objSelection.range
            objMergeFields.Add(objRange, "FirstName")
            objSelection.TypeText(" ")
            objRange = objSelection.range
            objMergeFields.Add(objRange, "LastName")
            objRange = objSelection.range
            objSelection.TypeParagraph()

            objRange = objSelection.range
            objMergeFields.Add(objRange, "Address")
            objSelection.TypeParagraph()
            objRange = objSelection.range
            objMergeFields.Add(objRange, "CityStateZip")


            InsertLines(2, objSelection)

            ' Right justify the line and insert a date field
            ' with the current date.
            objSelection.ParagraphFormat.Alignment = _
                   Word.WdParagraphAlignment.wdAlignParagraphRight
            objSelection.InsertDateTime( _
                  DateTimeFormat:="dddd, MMMM dd, yyyy", _
                  InsertAsField:=False)


            InsertLines(2, objSelection)

            ' Justify the rest of the document.
            objSelection.ParagraphFormat.Alignment = _
                   Word.WdParagraphAlignment.wdAlignParagraphJustify

            objSelection.TypeText("Dear ")
            objRange = objSelection.range
            objMergeFields.Add(objRange, "FirstName")
            'objDoc.select()
            objSelection.TypeText(",")

            InsertLines(2, objSelection)


            ' Create a string and insert it into the document.
            StrToAdd = "Thank you for your recent request for next " & _
                "semester's class schedule for the Electrical " & _
                "Engineering Department. Enclosed with this " & _
                "letter is a booklet containing all the classes " & _
                "offered next semester at State University.  " & _
                "Several new classes will be offered in the " & _
                "Electrical Engineering Department next semester.  " & _
                "These classes are listed below."
            objSelection.TypeText(StrToAdd)

            InsertLines(2, objSelection)

            ' Insert a new table with 9 rows and 4 columns.
            objRange = objSelection.range
            objDoc.Tables.Add(objRange, NumRows:=9, _
                 NumColumns:=4)

            With objDoc.Tables.Item(1)
                ' Set the column widths.
                .Columns.Item(1).SetWidth(51, Word.WdRulerStyle.wdAdjustNone)
                .Columns.Item(2).SetWidth(170, Word.WdRulerStyle.wdAdjustNone)
                .Columns.Item(3).SetWidth(100, Word.WdRulerStyle.wdAdjustNone)
                .Columns.Item(4).SetWidth(111, Word.WdRulerStyle.wdAdjustNone)
                ' Set the shading on the first row to light gray.
                .Rows.Item(1).Cells.Shading.BackgroundPatternColorIndex = _
                 Word.WdColorIndex.wdGray25
                ' Bold the first row.
                .Rows.Item(1).Range.Bold = True
                ' Center the text in Cell (1,1).
                .Cell(1, 1).Range.Paragraphs.Alignment = _
                          Word.WdParagraphAlignment.wdAlignParagraphCenter

                ' Fill each row of the table with data.
                FillRow(objDoc, 1, "Class Number", "Class Name", "Class Time", _
                   "Instructor")
                FillRow(objDoc, 2, "EE220", "Introduction to Electronics II", _
                          "1:00-2:00 M,W,F", "Dr. Jensen")
                FillRow(objDoc, 3, "EE230", "Electromagnetic Field Theory I", _
                          "10:00-11:30 T,T", "Dr. Crump")
                FillRow(objDoc, 4, "EE300", "Feedback Control Systems", _
                          "9:00-10:00 M,W,F", "Dr. Murdy")
                FillRow(objDoc, 5, "EE325", "Advanced Digital Design", _
                          "9:00-10:30 T,T", "Dr. Alley")
                FillRow(objDoc, 6, "EE350", "Advanced Communication Systems", _
                          "9:00-10:30 T,T", "Dr. Taylor")
                FillRow(objDoc, 7, "EE400", "Advanced Microwave Theory", _
                          "1:00-2:30 T,T", "Dr. Lee")
                FillRow(objDoc, 8, "EE450", "Plasma Theory", _
                          "1:00-2:00 M,W,F", "Dr. Davis")
                FillRow(objDoc, 9, "EE500", "Principles of VLSI Design", _
                          "3:00-4:00 M,W,F", "Dr. Ellison")
            End With

            ' Go to the end of the document.
            objApp.Selection.GoTo(Word.WdGoToItem.wdGoToLine, _
             Word.WdGoToDirection.wdGoToLast)

            InsertLines(2, objSelection)

            ' Create a string and insert it into the document.
            StrToAdd = "For additional information regarding the " & _
                       "Department of Electrical Engineering, " & _
                       "you can visit our Web site at "
            objSelection.TypeText(StrToAdd)
            ' Insert a hyperlink to the Web page.
            objRange = objSelection.range
            objSelection.Hyperlinks.Add(Anchor:=objRange, _
               Address:="http://www.ee.stateu.tld")
            ' Create a string and insert it in the document.
            StrToAdd = ".  Thank you for your interest in the classes " & _
                       "offered in the Department of Electrical " & _
                       "Engineering.  If you have any other questions, " & _
                       "please feel free to give us a call at " & _
                       "555-1212." & vbCr & vbCr & _
                       "Sincerely," & vbCr & vbCr & _
                       "Kathryn M. Hinsch" & vbCr & _
                       "Department of Electrical Engineering" & vbCr
            objSelection.TypeText(StrToAdd)

            ' Perform mail merge.
            objMailMerge.Destination = _
                       Word.WdMailMergeDestination.wdSendToNewDocument

            objMailMerge.Execute(False)

            ' Close the original form document.
            objDoc.Saved = True
            objDoc.Close(False)

            ' Release References.
            objSelection = Nothing
            objMailMerge = Nothing
            objMergeFields = Nothing
            objDoc = Nothing
            objApp = Nothing

            ' Clean up temp file.
            System.IO.File.Delete("C:\DataDoc.doc")

            Me.txtResults.Text = "No program Errors occurred !"

        Catch ex As Exception
            Dim strErr As String = ex.Message & vbCrLf & vbCrLf
            strErr += "Error Stack:" & vbCrLf
            strErr += ex.StackTrace
            Me.txtResults.Text = strErr
        End Try

    End Sub

    Private Sub btnButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnButton1.Click
        DoTheMerge()
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub
One of these days when I have some time on my hands, I'll figure out how to do this with Reflection using VB.NET...
Al Williams

Anola MB, CANADA
Previous
Reply
Map
View

Click here to load this message in the networking platform