I am having issues getting my embedded document to run on older version of MS Office. I believe the issue lies in how I am declaring my objects, but am unsure how to declare my embedded documents using late binding (I'm still very new to both this concept and vba). Below is how I'm currently doing my variable declaration along with a snippet of code. It works great in Excel 2013, but is not working in 2010 because of how I declared my variables (I believe).
Dim oDoc As Word.Document
Dim oTemplate As Word.Document
Dim wdObj As OLEObject
Dim wdObj2 As OLEObject
'Deselect anything selected
Range("A1").Select
'Copy content of template
Set wdObj = Sheets("Template").OLEObjects("Template")
wdObj.Activate
Set oTemplate = wdObj.Object
oTemplate.Content.Copy
'Initialize letter document
Set wdObj2 = Sheets("Report").OLEObjects("Letter")
wdObj2.Activate
Set oDoc = wdObj2.Object
'Erase contents and replace with clean template
oDoc.Content.Delete
oDoc.Range.PasteAndFormat _
wdFormatOriginalFormatting
I've attempted setting oDoc and oTemplate them "As Object" but am not sure how to link them back to a word object. Doing this simply caused the library reference to fail on the PasteAndFormat call's "wdFormatOriginalFormatting".
I've been tearing my hair out trying to figure this out. Any help would be greatly appreciated. Thanks!
First, ensure you're using Option Explicit
in the code module. THen, when you attempt to compile, it should alert you to a problem with wdFormatOriginalFormatting
.
Why?
wdFormatOriginalFormatting
is an enumerated constant within the Word object model. It doesn't exist in Excel, unless you use early binding.
Solution
When you use late-binding, you need to declare and assign values to these constants, since they are not otherwise known at compile time or run-time:
Const wdFormatOriginalFormatting as Long = 16
Then, this line should not cause the error:
oDoc.Range.PasteAndFormat _
wdFormatOriginalFormatting