I'm trying to create an automated report. So far I've managed to be able to create the word document from a template full of bookmarks, insert specific data from excel into the correct positions and finally to save the file as .docx and a random name.
My problem is that after all these bookmarks are updated I need to add a section break on bookmark "PgBrk" and create a new page. I don't mind preserving any bookmarks since any new file is being automatically saved with a new name; thus my template is always intact.
Been looking on the net for the last couple of days but always end up with some type of error, depending on what I've tried.
My code goes like this:
Sub REP_DET()
Dim Template_Path As String
Dim Template_Name As String
Dim LRandomNumber As Integer
Template_Path = Application.ActiveWorkbook.Path
Template_Name = "\template.docx"
Randomize
LRandomNumber = Int((9999 - 1000 + 1) * Rnd + 1000) 'Int ((min - max + 1) * Rnd + min)
Set wApp = CreateObject("Word.Application")
wApp.documents.Open (Template_Path & Template_Name)
wApp.Visible = True
Set wdoc = wApp.documents.Open(Template_Path & Template_Name)
With wdoc
.Bookmarks("Item_Code").Range.Text = Sheets("A").Range("H2").Value
' various figures are populated in designated bookmark positions within the doc file
end with
With wdoc
.Bookmarks("PgBrk").Range.Select
With Selection
.Collapse Direction:=0
.InsertBreak Type:=wdSectionBreakNextPage
End With
End With
With wdoc
.SaveAs2 Filename:=(Template_Path & "\template" & LRandomNumber & ".docx"), _
FileFormat:=wdFormatXMLDocument, AddtoRecentFiles:=False
End With
Any help appreciated.