Reputation: 502
I'm looping through a collection of strings (looking like "Figure 1"), finding every occurrence of those strings in a Word document, and trying to insert on each of them a cross reference to a caption (my captions follow this pattern "Figure 1 [00:01:20]"). For some reason, it totally fails on the line containing the "InsertCrossReference" method (throws a runtime error 4198 with the message "Command failed"). Here's a part of my code so far:
For Each Match In AllMatches 'for each word in my AllMatches collection
Set rngFind = ActiveDocument.Content
With rngFind.Find
.Forward = True
.ClearFormatting
.Text = Match.value
.Format = False
.MatchCase = False
.MatchWholeWord = True
.Wrap = wdFindStop
Do While .Execute
rngFind.InsertCrossReference ReferenceType:="Figure", _
ReferenceKind:=wdOnlyLabelAndNumber, _
ReferenceItem:=Match.value, _ 'Match.value looks like "Figure 1 [00:01:20]" (like in the picture below)
InsertAsHyperlink:=True, _
IncludePosition:=False, _
SeparateNumbers:=False, _
SeparatorString:=" "
Loop
End With
Next Match
I tried to investigate and found that "UBound(ActiveDocument.GetCrossReferenceItems(ReferenceType:="Figure"))" returns "0" (same when I use "wdCaptionFigure" as ReferenceType).
When I manually tries to insert the cross-reference, everything works (see the picture below)...
When I record the manual insert and tries to run the code generated by word, it fails!
Could the issue be caused by the fact the captions are inserted with VBA just before, on shapes rather than inlineshapes (with a loop and ".InsertCaption Label:=wdCaptionFigure" etc.)?
---- EDIT ----
Here's are some steps that trigger the error, and seem to confirm that inserting the caption on shapes rather than inlinshapes cause the cross-reference error later on.
Select "I am a test" and run the following macro:
Sub Macro1() Selection.InsertCrossReference ReferenceType:="Figure", ReferenceKind:=wdEntireCaption, ReferenceItem:="1", InsertAsHyperlink:=True, IncludePosition:=False, SeparateNumbers:=False, SeparatorString:=" " End Sub
This triggers the 4198 error. If you omit the step 3 and the step 5, there's no error. I'm totally stuck on this one. I'll be very glad if one of you could help me.
Upvotes: 0
Views: 531
Reputation: 126
I had a similar problem. I solved it by creating an array, saving the range to the array within the .Execute loop, and then looping through the array after find is done to insert the cross reference. Here is an example:
Dim docRange As Range
Set docRange = ActiveDocument.Content
Dim terms() As Range, X As Long
X = 0
With docRange.Find
...
While .Execute
docRange.Select
If .found Then
ReDim Preserve terms(X)
Set terms(X) = Selection.Range
X = X + 1
End If
Selection.Collapse
Wend
End With
Dim i As Integer
For i = 0 To UBound(terms)
terms(i).InsertCrossReference _
ReferenceType:=wdRefTypeBookmark, _
ReferenceKind:=wdContentText, _
InsertAsHyperlink:=True, _
ReferenceItem:=mark
Next i
Upvotes: 0