Home » excel » vba – Selection member methods

vba – Selection member methods

Posted by: admin April 23, 2020 Leave a comment


I am trying to write code that:

  1. Finds/locates specific strings that appear in the first column of tables in a Word document.
  2. Maps these strings to the immediate headings of the tables that they appear in.
  3. List out the string-heading mappings in an Excel spreadsheet.
    Caveat: All of the strings the VBA code will look for are listed under an existing Excel spreadsheet.

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.

How to&Answers:

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.