I have a Word document containing a few lines of text and a table with many place holders I will fill in from Excel later in the same document but saving it as PDF.
My final goal is to duplicate the whole text in the word file as it is before any modification and paste it every time I have to complete it with the values in the Excel file.
Inside word VBA, this works perfectly. Copy the whole document and past it at the end, duplicating the table and the lines of text.
Selection.WholeStory
Selection.Copy
Selection.MoveDown Unit:=wdParagraph, Count:=2
Selection.PasteAndFormat (wdFormatOriginalFormatting)
And in Excel VBA, I have this working just fine. Except the * Asterics part, I don't know how to execute the code that works in Word VBA from Excel VBA.
Sub GenerateDoc()
DocLoc = Application.ActiveWorkbook.Path & "\CategoryTable2.docx"
'Open Word Template
With Sheet2
On Error Resume Next 'If Word is already running
Set WordApp = GetObject("Word.Application")
If Err.Number <> 0 Then
'Launch a new instance of Word
Err.Clear
'On Error GoTo Error_Handler
Set WordApp = CreateObject("Word.Application")
End If ' Work Running Check
WordApp.Visible = True 'Make the application visible to the user
Set WordDoc = WordApp.Documents.Open(Filename:=DocLoc, ReadOnly:=False) 'Open Template
'This is not workin, no error throw however
'*****************************************
WordDoc.Content.WholeStory
WordDoc.Content.Copy
'***************************************
For component = 15 To 150
iRow = component
If .Cells(iRow, 1).Value = 0 And .Cells(iRow, 2).Text <> "" Then
For CustCol = 3 To 85 'Move Through Columns
If Left(.Cells(13, CustCol).Text, 1) = "[" And Right(.Cells(13, CustCol).Text, 1) = "]" Then
varName = .Cells(13, CustCol).Value 'Determine Variable Name
'varName = "[" & varName & "]"
VarValue = Trim(.Cells(iRow, CustCol).Text) 'Determine Variable Value
With WordDoc.Content.Find
.Text = varName
.Replacement.Text = Application.WorksheetFunction.Text(VarValue, "General")
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll 'Find & Replace all instances
End With
End If
Next CustCol
End If
Next component
'This is not working, no error throw however
'**************************************************************************
WordDoc.Content.MoveDown Unit:=wdParagraph, Count:=2
WordDoc.Content.PasteAndFormat (wdFormatOriginalFormatting)
'**************************************************************************
Filename = Application.ActiveWorkbook.Path & "\ComponentsTable.pdf" 'Create full filename & Path with current workbook location, Last Name & First Name
On Error Resume Next
Kill (Filename) 'Delete filename with the same name if it exists
On Error GoTo 0
On Error Resume Next
WordDoc.ExportAsFixedFormat OutputFileName:=Filename, ExportFormat:=wdExportFormatPDF
WordDoc.Close False
WordApp.Quit
Set WordDoc = Nothing
Set WordApp = Nothing
End With
End Sub