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