Hello my friends.
I have an Excel document which acts as a small database. A report button is incorporated which has to extract the database data and export it to a Word file.
I first want to filter data in the excel database with the standard Filter capability of Excel and export that data to a template Word document with bookmarks. However, I do not have the capabilities to create such code.
Can someone help me out? I am puzzling with the following code, but it creates separate Word files and my goal is one Word file.
I have an Excel document which acts as a small database. A report button is incorporated which has to extract the database data and export it to a Word file.
I first want to filter data in the excel database with the standard Filter capability of Excel and export that data to a template Word document with bookmarks. However, I do not have the capabilities to create such code.
Can someone help me out? I am puzzling with the following code, but it creates separate Word files and my goal is one Word file.
Code:
Option Explicit'change this to where your files are stored
Const FilePath As String = "C:\reporttemplate.docx"
Dim wd As New Word.Application
Dim IDCell As Range
Sub Sheet5_Button2_Click()
'create copy of Word in memory
Dim doc As Word.Document
wd.Visible = True
Dim IDRange As Range
'create a reference to all the ids
Range("A1").Select
Set IDRange = Range( _
ActiveCell, _
ActiveCell.End(xlDown))
'for each person in list �
For Each IDCell In IDRange
'open a document in Word
Set doc = wd.Documents.Open("C:\reporttemplate.docx")
'go to each bookmark and type in details
CopyCell "id", 1
CopyCell "date", 2
CopyCell "risk", 3
'save and close this document
doc.SaveAs2 FilePath & "report " & IDCell.Value & ".docx"
doc.Close
Next IDCell
wd.Quit
MsgBox "Created files in " & FilePath & "!"
End Sub
Sub CopyCell(BookMarkName As String, ColumnOffset As Integer)
'copy each cell to relevant Word bookmark
wd.Selection.Goto What:=wdGoToBookmark, Name:=BookMarkName
wd.Selection.TypeText IDCell.Offset(0, ColumnOffset).Value
End Sub