0
votes

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.

1
If you remove the library reference then 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). Adding option explicit to the top of your modules would highlight this error)Alex K.

1 Answers

0
votes

If you don't know the numerical equivalent then:

  • Open the application in question (in your case Word)
  • Open the VBE (Alt + F11)
  • Open the Immediate window (Ctrl + G)
  • Enter the keyword in the immediate window preceded by a ? (?wdStory)
  • Use the number it returns in your code.

In this case you need to replace wdStory with the number 6.
(and just read the middle line of @AlexK comment - add a reference temporarily and ?wdStory in the immediate window to see what it is)
Never thought of adding the referencing and using the immediate window in the current app. I know I'd forget to remove it again though.