Basically, I have a ListBox in my Userform and table with the same columns and rows of the ListBox. My ListBox items are from Excel in Sheet3 using a range source Sheet3(A1:C6). What I wanted to do is when I click the command button all the items in the ListBox will be transferred to my MS word table.
This is my current code. Unfortunately, Nothing's happening and I have no idea why.
I have attached a sample image.
Set WordApp = New Word.Application
Set WordDoc = WordApp.Documents.Open(DocFile, False)
Word.Application.Visible = True
For lnglistcount = 0 To ListBox1.List - 1
WordDoc.Content.InsertAfter Text:=ListBox1.List(lnglistcount)
WordDoc.ExportAsFixedFormat OutputFileName:=FilePath, ExportFormat:=wdExportFormatPDF
WordDoc.Close saveChanges:=False
WordApp.Quit
Set WordApp = Nothing
Set WordDoc = Nothing
MsgBox "File Created."
Next
CodePudding user response:
This code assumes the document already exists, has a table of the right size (ie number of rows and columns and no merged cells etc) and that it is the first table in the document. Also assuming that your Excel VBA project has a reference to the Microsoft Word Object Library.
Dim WordApp As Word.Application, WordDoc As Word.Document
Set WordApp = New Word.Application
Set WordDoc = WordApp.Documents.Open(DocFile, False)
WordApp.Visible = True
Dim values As Variant, row As Long, col As Long
values = ListBox1.List
For row = 0 To UBound(values, 1)
For col = 0 To UBound(values, 2)
WordDoc.Tables(1).Cell(row 1, col 1).Range.Text = values(row, col)
Next col
Next row
WordDoc.Close SaveChanges:=True
WordApp.Quit