Replacement works only once

Michael O.

I need to find patterns in TeX notation and change its formatting. For example, for text like this:

$I_{CC}$, $U_{CC}$, $A_U$ 

replacement should be

enter image description here

Here is a script to do this:

Sub probe()
'
Dim doc As Document
Dim r As Range
Dim r2 As Range
Set doc = ActiveDocument
Set r = doc.Range
With r.Find
    .ClearFormatting
    .Text = "$?*_?*$"
    .MatchWildcards = True
    .Execute
    While .Found
        Debug.Print r.Text
        t = r.Text
        und = InStr(1, t, "_")
        Set r2 = r
        t = r2.Text
        t = Replace(t, "_", "")
        t = Replace(t, "{", "")
        t = Replace(t, "}", "")
        t = Replace(t, "$", "")
        r2.Text = t
        r2.MoveStart wdCharacter, und - 2
        r2.Font.Subscript = True
        .Execute
    Wend
End With
End Sub

It works, but replaces only the first found text. As I understand, it happens because the command Set r2 = r does not copy a range, but does equate r and r2. How to solve my problem?

Cindy Meister

Word Ranges are different from everything else in VBA - they're actual "pointers" to the object. So if you set one range equal to another, they're exactly the same object. Changing one changes the other.

Therefore, it's necessary to "copy" a range if you need a second, independent instance to work with. That's done using the Duplicate method:

Set r2 = r.Duplicate

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related