View Single Post
 
Old 07-03-2022, 04:31 AM
Guessed's Avatar
Guessed Guessed is offline Windows 10 Office 2016
Expert
 
Join Date: Mar 2010
Location: Canberra/Melbourne Australia
Posts: 3,977
Guessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant future
Default

Try this code. Put it in your Excel workbook and add a reference to "Microsoft Word x.x Object Library".

Before running the macro, make sure the correct worksheet is active.

This code is putting a duplicate of the first table at the end of the document and adding the Excel data into that new table. It repeats for each pair of rows in Excel.
Code:
Sub Write2Word()
  Dim wdDoc As Word.document, wdTbl As Word.Table, wdApp As Object, wdRng As Word.Range
  Dim iRow As Integer, aSheet As Worksheet, iCol As Integer, iPair As Integer
  Dim sPath As String
  Set aSheet = ActiveSheet
  iRow = 2
  sPath = ActiveWorkbook.Path & "\"
  Set wdApp = CreateObject("Word.Application")
  wdApp.Visible = True
  
  Set wdDoc = wdApp.Documents.Add(sPath & "OUTPUT_RESULT-FILE.docx")  'creates new doc based on this file
  
  Do While aSheet.Cells(iRow, 1).Value <> ""
    Set wdRng = wdDoc.Range
    wdRng.Collapse Direction:=0
    wdRng.InsertBefore Chr(13) & Chr(13)
    wdRng.Collapse Direction:=0
    wdRng.FormattedText = wdDoc.Tables(1).Range.FormattedText
    Set wdTbl = wdRng.Tables(1)
    For iPair = 0 To 1
      For iCol = 0 To 7
        wdTbl.Cell(iCol + 1, iPair + 2).Range.Text = aSheet.Cells(iRow, 1).Offset(iPair, iCol).Value
      Next iCol
    Next iPair
    iRow = iRow + 2
  Loop
End Sub
__________________
Andrew Lockton
Chrysalis Design, Melbourne Australia
Reply With Quote