A
A
Alexandr_ABS2021-02-20 07:10:30
Visual Basic
Alexandr_ABS, 2021-02-20 07:10:30

How to insert a table in MS Word using VBA?

I am writing a code in VBA so that information from a MS Excel file is unloaded into a separate MS Word file. I can't figure out how to insert a table after text. Help me please. At the moment the code looks like this:

Sub test()
    Dim oWord As Object 
    Dim oDoc As Object    
sText = "ОБРАЗЕЦ ТЕКСТА" + vbCr + vbCr
    Set oWord = CreateObject("Word.Application")
    oWord.Visible = True
    Set oDoc = oWord.Documents.Add(DocumentType:=0)
    oWord.Activate
    With oWord.Selection
        .Font.Name = "Times New Roman"
        .Font.Size = 8
        .ParagraphFormat.Alignment = 2
        .TypeText (sText)
        .TypeParagraph
        .TypeParagraph
    End With
   ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=2, NumColumns:= _
        2, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
        wdAutoFitFixed
    With oWord.Selection
        .Font.Name = "Times New Roman"
        .Font.Size = 8
        .ParagraphFormat.Alignment = 2
        .TypeText Text:="ТЕКСТ пробного курса №5"
        .TypeParagraph
        .TypeParagraph
    End With
End Sub

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BasiC2k, 2021-02-20
@BasiC2k

There are two ways to transfer a table to Word with a macro:
1. Transfer by an object through the Windows clipboard. Those. in Excel, select table cells and copy to clipboard. Then, in Word, put the cursor in the right place and paste the contents of the clipboard. The disadvantage of this method is that not only you can work with the buffer at this time;
2. Create a Word table. Those. macro in Excel pulls out the contents of the table and then creates and populates the created table.
Both methods are applicable. But my opinion is that working with tables is easier in Excel.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question