EmilyR
EmilyR

Reputation: 21

call GetCrossReferenceItems(wdRefTypeHeading) in excel

I am trying export the excel content into a word document using a template.

There are different heading levels in the word template. I need to get the heading list so that I can insert the content from excel into the proper location. However, GetCrossReferenceItems(wdRefTypeHeading) is not working.

Here is the code:

Private Sub CommandButton1_Click()
    Set wdObj = CreateObject("Word.Application")
    wdObj.Visible = True
    wdObj.Documents.Open FileName:="test.dotx"
    Set wdDoc = wdObj.ActiveDocument
    astrHeadings = wdDoc.GetCrossReferenceItems(wdRefTypeHeading)
    MsgBox ("headings #" & UBound(astrHeadings)) 'correct number if in word, 0 if in excel
    wdObj.Quit
End Sub

I can get the list if I put the exactly same code in a word document, but the list will be always empty (ubound(~) = 0) if I put the same code in a excel.

Why does this happen?

Upvotes: 2

Views: 1526

Answers (1)

Siddharth Rout
Siddharth Rout

Reputation: 149335

You are Late Binding with MS Word and hence MS Excel cannot understand what wdRefTypeHeading is. For MS Excel the value of that variable is 0 whereas for MS Word the value of that constant is 1.

Try this. (TRIED AND TESTED)

Const wdRefTypeHeading = 1

Sub Sample()
    Dim wdObj As Object, wdDoc As Object
    Dim FlName As String
    Dim astrHeadings

    Set wdObj = CreateObject("Word.Application")
    wdObj.Visible = True
    FlName = "C:\test.dotx"
    Set wdDoc = wdObj.Documents.Open(FlName)

    astrHeadings = wdDoc.GetCrossReferenceItems(wdRefTypeHeading)

    MsgBox ("headings #" & UBound(astrHeadings))

    wdObj.Quit

    '~~> Close and Clean Up
    Set wdDoc = Nothing
    Set wdObj = Nothing
End Sub

Upvotes: 3

Related Questions