Search code examples
.netvb.netvisual-studio-2015ms-wordoffice-interop

visual studio 2015 create text box or anything in microsoft word document


Is it possible to create a table/shape/text box in a Microsoft Office Word Document using VB in Visual Studio 2015?

All I can find online is to create a document/save it/close word. I am trying to create a table given certain values a user will decide.


Solution

  • Found This example at MSDN. Dont forget to add a reference to Microsoft.Office.Interop.Word

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        CreateTableInWordDocument()
    End Sub
    
    Private Sub CreateTableInWordDocument()
        Dim objWord As Application
        Dim objDoc As Document
        Dim objTable As Table
        objWord = CreateObject("Word.Application")
        objWord.Visible = True
        objDoc = objWord.Documents.Add
        Dim r As Integer, c As Integer
    
        objTable = objDoc.Tables.Add(objDoc.Bookmarks.Item("\endofdoc").Range, 3, 5)
        objTable.Range.ParagraphFormat.SpaceAfter = 6
        For r = 1 To 3
            For c = 1 To 5
                objTable.Cell(r, c).Range.Text = "Row" & r & " Coulmn" & c
            Next
        Next
        objTable.Rows.Item(1).Range.Font.Bold = True
        objTable.Rows.Item(1).Range.Font.Italic = True
    
    End Sub