Consulting

Results 1 to 2 of 2

Thread: Selection.Range Type Mismatch

  1. #1
    VBAX Newbie
    Joined
    Jul 2014
    Posts
    1
    Location

    Selection.Range Type Mismatch

    I have code that gets the range of each heading in a word document. The headings' ranges are saved in HeadingRange(). I am getting Run-Type Error 13: type mismatch when I set HeadingRange(HeadingCount) in my For loop. I don't know why this is happening. Both HeadingRange() and wrdApp.Selection.Range are clearly instances of the Range class.
    Note: This subroutine is called from a VBA Excel program, not Word.

    Private Sub WordTab()
    
    Dim wrdDoc As Word.DocumentDim wrdApp As Word.Application
    Set wrdApp = CreateObject("Word.Application")
    wrdApp.Visible = True
    Set wrdDoc = wrdApp.Documents.Open("C:/Test.docx")
    
    
    Dim i As Integer 
    Dim myHeadings As Variant
    Dim count As Integer
    Dim HeadingRange() As Range
    Dim HeadingCount as Integer
    
    
    TableCount = wrdDoc.Tables.count
    wrdApp.Selection.HomeKey Unit:=wdStory  'moves selection to beginning of doc. assuming document's first line is not a heading.
    myHeadings = wrdDoc.GetCrossReferenceItems(wdRefTypeHeading)
    
    ReDim HeadingRange(1 To 1)
    
    HeadingCount = 1
    For i = LBound(myHeadings) To UBound(myHeadings) 'iterate through all headings
    
        wrdApp.Selection.GoTo What:=wdGoToHeading, Which:=wdGoToNext 'move selection to next heading. 
        wrdApp.Selection.Expand wdLine 'expand selection range to entire line
    
        ReDim Preserve HeadingRange(1 To HeadingCount)
        Set HeadingRange(HeadingCount) = wrdApp.Selection.Range 'This is where the type mismatch happens
        HeadingCount = HeadingCount + 1
    
    
    Next i
    
    wrdDoc.Close (Word.WdSaveOptions.wdDoNotSaveChanges)
    Debug.Print "Done"
    
    End Sub

  2. #2
    Microsoft Word MVP 2003-2009 VBAX Guru gmaxey's Avatar
    Joined
    Sep 2005
    Posts
    3,340
    Location
    I'm not familiar with the Excel range object, but try changing:

    Dim HeadingRange() As Range
    to:
    Dim HeadingRange() As Variant 'or
    'Dim HeadingRange() As Word.Range
    Greg

    Visit my website: http://gregmaxey.com

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •