vbams-wordword-style

how to assign table styles with code to a word document


I'm creating a word document with data from a Visual Basic 2010 software I created for my work, which consist in a report ... i was ask to generate a Microsoft word document, so now I'm creating a table and filling that table with data, something likes this

oTable = oDoc.Tables.Add(oDoc.Bookmarks.Item("\endofdoc").Range, 8, 4)
oTable.Range.ParagraphFormat.SpaceAfter = 6
oTable.Range.Font.Size = 10

oTable.Rows.Item(1).Range.Font.Bold = True
oTable.Rows.Item(1).Range.Font.Italic = True
oTable.Cell(1, 1).Range.Text = "Datos de Facturación:"
oTable.Cell(1, 3).Range.Text = "            Enviar a:"
oTable.Cell(2, 1).Range.Text = rs.Text
oTable.Cell(2, 1).Width = 75
oTable.Cell(3, 1).Range.Text = dirfa.Text
oTable.Cell(3, 1).Width = 75 ..... etc..

Microsoft Word has some table designs styles like "DARK LIST - ACCENT 5". "DARK LIST - ACCENT 6" etc, I couldn't figure out how to set this styles to the table, is it possible?


Solution

  • To create a style, you can use a document object:

    Set doc = wd.Documents.Add(NewTemplate:=True)
    
    With doc.Styles("Certificate")
        With .Font
            .Name = "Arial"
            .Size = 12
            .Italic = True
            .Bold = True
        End With
    
        With .ParagraphFormat
            ''wdAlignParagraphCenter = 1
            .Alignment = 1
            .SpaceAfter = 0
            .SpaceBefore = 0
        End With
    End With
    

    Assign the style:

    Set r = doc.Shapes("Course1").TextFrame.TextRange
    r.Style = "Certificate"
    

    For this particular case, you might use:

        oTable.Range.Style = "ANewStyle"
    

    Or if built-in styles are available to you:

        oTable.Rows.Item(1).Range.Style = WdBuiltinStyle.wdStyleHeading1