Hi,
I have written a piece of code whereby from Excel VBA, I will be inserting some texts to some Word Content.Control Fields and in some instances, inserting email address hyperlink to Word Bookmarks.
The piece of code works the first time but will fail when running it again. Also, it does not work if I do not make Word Visible. Any guidance is much appreciated.
Andrew
Code
Sub testBookmark1()
Dim WordApp As Word.Application
Dim objDoc As Word.Document
Dim strPath, strFileName, strOutPutFileName As String
Dim objRange As Word.Range
Dim cc As ContentControl
'Set Path Name
strPath = "C:\Testing\Tool\"
'Set File Name
strFileName = "Test.docx"
'Set Output File Name
strOutPutFileName = "Test1.pdf"
'Create the object of Microsoft Word
Set WordApp = New Word.Application
'Create Doc object using MS word object, Open the existing word document by providing the complete path
Set objDoc = WordApp.Documents.Open(strPath & strFileName)
'Make the MS Word Visible
WordApp.Visible = True
'Get the range object for the Client_Name bookmark
Set objRange = ActiveDocument.Bookmarks("Client_Name").Range
objRange.Text = "ABC Company"
'Get the range object for the bookmark
Set objRange = ActiveDocument.Bookmarks("Team_Email").Range
'Insert the text AFTER the bookmark
ActiveDocument.Hyperlinks.Add Anchor:=objRange, Address:= _
"mailto:[email protected]", SubAddress:="", ScreenTip:="", TextToDisplay:= _
"[email protected]"
'Content Control
For Each cc In WordApp.ActiveDocument.ContentControls
If cc.Title = "EQ_Box" Then
cc.Checked = True
End If
If cc.Title = "Cap_Box" Then
cc.Checked = True
End If
Next cc
'Save The File
WordApp.ActiveDocument.ExportAsFixedFormat OutputFileName:= _
strPath & strOutPutFileName, ExportFormat:=wdExportFormatPDF, _
OpenAfterExport:=False, OptimizeFor:=wdExportOptimizeForPrint, Range:= _
wdExportAllDocument, From:=1, To:=1, Item:=wdExportDocumentContent, _
IncludeDocProps:=False, KeepIRM:=False, CreateBookmarks:= _
wdExportCreateHeadingBookmarks, DocStructureTags:=True, _
BitmapMissingFonts:=False, UseISO19005_1:=False
'Close the File
WordApp.ActiveDocument.Close SaveChanges:=False
'release the memory
Set objDoc = Nothing
Set WordApp = Nothing
MsgBox ("Completed")
End Sub
Display More