I am trying to write code that:
So far, I have been able to figure out #1 and #3 fairly easily. I figured #2 will need to use of the Selection class. I have been trying to familiarize myself with it but I am having a lot of trouble. For example, I have written a simple subroutine that resets the selection cursor to the beginning of a word document. This sub is called from a main sub in an Excel VBA.
Private Sub FindHeadings()
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Open("C:/Users/c11145/Desktop/SSDD_Trace/Test3.docx")
'wrdDoc.Selection.HomeKey Unit:=wdStory
Selection.HomeKey Unit:=wdStory
End Sub
I am getting Run-time error "438": Object doesn't support this property or method.
I have also tried:
Dim sel As Selection
sel.HomeKey Unit:=wdStory
But I get Run-time error 91.
I think you need to qualify your Selection because that is an available class in Excel, too.
I am pretty sure that whenever a classname may be shared by multiple libraries, the shortest reference (i.e., the active application's) is the default, so unless you qualify Selection will always refer to the Excel selection (shape, cell/range, etc.)
When I run something very simple in Word (not from Excel), I think this does what you need:
Sub test()
Dim wrdDoc As Word.Document
Dim wrdApp As Word.Application
Set wrdDoc = ActiveDocument
Set wrdApp = wrdDoc.Parent
wrdApp.Selection.HomeKey Unit:=wdStory
End Sub
Porting this over to Excel, try qualifying Selection as a member of the wrdApp:
wrdApp.Selection.HomeKey Unit:=6 'wdStory
The reason I use 6 instead of the enumerated constant wdStory is because the latter will fail unless you are using early binding with explicit reference to the Word object model. If you are not doing early binding, then wdStory is essentially an undeclared variable with an empty value, which will raise a "Bad Parameter" errror on that line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With