suggestion VBA for replacing all occurences of a string with wildcard

E

Enda

Hi,
I would appreciate some help with the following.

I would like to search a given document for the following string:
"\ref{*}}" where * can be any combination of characters. I gather this
must be represented by "\ref\{*\}\}"

and replace it by the same String less the trailing curly brace.

The range.Find method only returns a boolean so I don't know how to
get a handle on the found text to remove its trailing }.

Any advice would be grately appreciated.

Enda Ridge
 
D

Dave Lett

Hi Enda,

First, are these fields? If so, then Word cannot find the brace delimiters
of the field. You'll need a different routine than the ones I've suggested
here.

Why not just replace "}}" with "}"?
With Selection
.HomeKey Unit:=wdStory
With .Find
.ClearFormatting
.Text = "}}"
With .Replacement
.ClearFormatting
.Text = "}"
End With
.Execute Replace:=wdReplaceAll
End With
End With

If, for some reason, you must have a wildcard search, then you can use the
following:
With Selection
.HomeKey Unit:=wdStory
With .Find
.ClearFormatting
.Text = "(\\ref\{*\})(\})"
.MatchWildcards = True
With .Replacement
.ClearFormatting
.Text = "\1"
End With
.Execute Replace:=wdReplaceAll
End With
End With

Dave
 
E

Enda

Hi Dave,
Thanks for all your help. I've included my implementation of your
solution below.
To clarify the original problem for the benefit of others, I wanted to
replace all occurences of a String "\ref{.....}}" with the same string
less the final closing brace. The strings were not part of a field. In
fact, they're latex commands in a plain text file.

Thanks again,

Enda

---------------------------------------------------------------------------
Public Sub repairCrossReferences(doc As Document)

On Error GoTo ErrHandler


Dim docRange As Range
Dim foundRange As Range

Set docRange = doc.Content

With docRange
'.HomeKey Unit:=wdStory
With .Find
.ClearFormatting
.Text = "(\\ref\{*\})(\})"
.MatchWildcards = True
With .Replacement
.ClearFormatting
.Text = "\1"
End With
.Execute Replace:=wdReplaceAll

End With
End With

Exit Sub

ErrHandler:
Dim routine As String
routine = "repairCrossReferences "

Select Case Err.Number
Case Else
MsgBox routine _
& vbNewLine & Error(Err) _
& vbNewLine & Err.Number _
& vbNewLine & Err.Description _
& vbNewLine & Err.Source

End Select
End Sub
----------------------------------------------------------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top