Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InsertCrossReference Fails On Last Item

I think I have found a bug with the InsertCrossReference. If I use from code for the last list item in the document and there being nothing after that list item, it fails with error "Run-time error '4198' Command failed". If you do it manually, it all works. So you are thinking, I have written the code incorrectly, but this isn't the case. To make sure, i recorded a macro of inserting the cross reference and then ran the macro it recorded and the same error happens.

I have googled this problem and seen a couple of people raise it but a)they haven't pointed out that it only fails for the last list item and there being nothing in the document after that list item b)they haven't had any work-around replies.

I am using Word 2010 but I have also tried it on Word 2013 and the same thing happens.

If you want an example, if I set up the following:

This is my xref

  1. Hello
  2. Bye

where 1 and 2 are standard numbered lists and I have nothing in the document after "Bye" and then I run:

ActiveDocument.Range(16, 16).InsertCrossReference ReferenceType:="Numbered item", _
ReferenceKind:=wdNumberFullContext, ReferenceItem:="2", InsertAsHyperlink _
:=True, IncludePosition:=False, SeparateNumbers:=False, SeparatorString:=" "

Note having nothing after "Bye" is key. If you start a new line, with or without a list type, the code above will work

If anyone has any work-around for this, I'd appreciate it

like image 604
crookie Avatar asked Apr 27 '26 19:04

crookie


1 Answers

You cannot insert anything AFTER the last paragraph mark in a document. I've had this issue in the past. My work around was to pragmatically add a paragraph mark in.

Something like the following:

Dim CRRange as Word.Range 'Make a range object to store where the cross reference will go.
set CRRange = ActiveDocument.Range(16,16)

if CRRange.end >= ActiveDocument.Range.End then 'Check to see if we reached the end of the document
    ActiveDocument.Paragraphs.Add Range:=ActiveDocument.Range(ActiveDocument.Range.End -1, ActiveDocument.Range.End -1)
End If

CRRange.InsertCrossReference ReferenceType:="Numbered item", _
    ReferenceKind:=wdNumberFullContext, ReferenceItem:="2", InsertAsHyperlink _
    :=True, IncludePosition:=False, SeparateNumbers:=False, SeparatorString:=" "
like image 150
gNerb Avatar answered Apr 29 '26 11:04

gNerb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!