confusedDude
confusedDude

Reputation: 25

Unable to insert a cross reference to a bookmark in specified cell in Word through with VBA

I am trying to cross reference a bookmark into the 2nd row of a column in a Word document, however, the bookmark keeps on being inserted in the first column. This is strange as I have selected the correct cell before inserting the cross reference.

Does anyone know why this is happening, or have any alternative methods of inserting a cross reference?

FYI the row selection seems to work fine each time.

NoOfTables = WordObject.ActiveDocument.Tables.Count
For t = 1 To NoOfTables
    If WordObject.ActiveDocument.Tables(t).Title = "AsetRsetTbl" Then
        WordObject.ActiveDocument.Tables(t).Cell(2, 2).Select
        WordObject.Selection.InsertCrossReference ReferenceType:="Bookmark", _
            ReferenceKind:=wdContentText, ReferenceItem:=BookMarkName & y, _
            InsertAsHyperlink:=True, IncludePosition:=False, _
            SeparateNumbers:=False, SeparatorString:=" "
    End If
Next t

Upvotes: 0

Views: 277

Answers (1)

Cindy Meister
Cindy Meister

Reputation: 25703

The following works. The key is how you specify where the cross-reference should go. I don't know "why", but when you select the entire cell Word decides the insertion point is in the previous cell. It probably has something to do with the cell structures in Word - only the people who wrote the underlying Word code know, for sure.

But, in any case, the trick is to do it as a user would. Usually, a user will click in a cell, so that the insertion point (cursor) is blinking.

Because, as with Excel, it's always better to not work with Selection, I've changed the code to use a Range object to target where the cross-reference goes. Whether you use Range or Selection - the key is to collapse the selection (like pressing the left or right arrow key on the keyboard).

I also changed to the code to make it more efficient and accurate, working with a Document object instead of ActiveDocument, which could change without your being aware of it.

Sub XRefInTable()
    Dim WordObject As word.Application
    Dim doc As word.Document
    Dim tbl As word.Table
    Dim rngCell As word.Range
    Dim t As Long, NoOfTables As Long

    Set WordObject = New Word.Application
    Set doc = WordObject.ActiveDocument
    NoOfTables = doc.Tables.Count
    For t = 1 To NoOfTables
        If doc.Tables(t).Title = "AsetRsetTbl" Then
            Set rngCell = doc.Tables(t).Cell(2, 2).Range
            rngCell.Collapse wdCollapseStart
            rngCell.InsertCrossReference ReferenceType:="Bookmark", _
                ReferenceKind:=wdContentText, ReferenceItem:=bookmarkname & y, _
                InsertAsHyperlink:=True, IncludePosition:=False, _
                SeparateNumbers:=False, SeparatorString:=" "
        End If
    Next t
End Sub

Upvotes: 0

Related Questions