I have a macro launched from Excel to control a Word document.
In order to prevent issues with references (Microsoft Word 15.0 Object Library or Microsoft Word 16.0 Object Library for example) I use late binding in the main macro :
Public appWord as Object
Sub MainSub()
Set appWord = GetObject(, "Word.Application")
If appWord Is Nothing Then
Set appWord = CreateObject("Word.Application")
End If
'Create temp file'
'...'
'Open temp file = strTempWordFile'
Set docWord = appWord.Documents.Open(strTempWordFile)
'Launch function to search text and remove it from the word document
SearchAndRemove rgCell2.Text, docWord
End Sub
Here is an extract of the function (in another module)
Sub SearchAndRemove(ByVal strSearchWord As String, ByRef docWord As Word.Document)
Set selWordSelection = appWord.Selection 'That works
selWordSelection.HomeKey Unit:=wdStory 'line with issue
'do the search and remove'
End Sub
If the Sub is called via declaring docWord as Word.Document (which requires reference to Microsoft Word 1X.0 Library, this line works OK :
selWordSelection.HomeKey Unit:=wdStory
If the Sub is called via declaring docWord as Object (which does not require reference to Microsoft Word 1X.0 Library, this line does not work anymore.
wdStory
is an unknown value, replace it with its true literal value (add a reference temporarily and ?wdStory in the immediate window to see what it is). Addingoption explicit
to the top of your modules would highlight this error) – Alex K.