Selection.Range类型不匹配

时间:2014-07-07 15:52:37

标签: vba word-vba

我有代码可以获取word文档中每个标题的范围。标题'范围保存在HeadingRange()中。当我在For循环中设置HeadingRange(HeadingCount)时,我得到Run-Type Error 13:类型不匹配。我不知道为什么会这样。 HeadingRange()和wrdApp.Selection.Range都是Range类的实例。

Private Sub WordTab()

Dim wrdDoc As Word.Document
Dim 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)

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

1 个答案:

答案 0 :(得分:0)

首先将数组重建为某个虚拟大小。您正在尝试Preserve一个不存在的数组。

所以你可以添加一个

Redim HeadingRange(1 To 1)

开始时的代码,在循环开始之前。