Цикл по всему документу Word Создание части текста надстрочного индекса - PullRequest
0 голосов
/ 30 сентября 2019

Я не могу понять, как перебрать текстовый документ, используя поиск и замену.

Я пытался использовать для каждого по-разному, но я не могу найти ничего, что работает. Я новичок в VBA и мало знаю об использовании объектов в программировании.

Sub Find()

    Dim Rng As Range
    Dim Fnd As Boolean


    Set Rng = Selection.Range
    With Rng.Find
        .ClearFormatting
        .Execute FindText:="4th", Forward:=True, _
                 Format:=False, Wrap:=wdFindStop
        Fnd = .Found
    End With

    If Fnd = True Then
        With Rng
            .MoveStart wdCharacter, 1
            .Font.Superscript = True

        End With
    End If

    Do Until Fnd = False
        With Rng.Find
            .ClearFormatting
            .Execute FindText:="4th", Forward:=True, _
                     Format:=False, Wrap:=wdFindStop
            Fnd = .Found
        End With

        If Fnd = True Then
            With Rng
                .MoveStart wdCharacter, 1
                .Font.Superscript = True
            End With
        End If
    Loop

End Sub

Я ожидаю, что цикл пройдёт и изменит последние 2 цифры каждого экземпляра, где в документе word найдена строка '4th', но он изменяет только первый экземпляр слова«4-й», а затем завершает программу. В конечном счете мне нужно будет заменить все экземпляры последних 2 символов 1-го, 2-го, 3-го и т. Д. На верхние индексы. Я не смог найти подстановочный знак для этого, поэтому, если это возможно сделать с использованием подстановочного знака, пожалуйста, дайте мне знать и включите код. Спасибо!

1 Ответ

0 голосов
/ 01 октября 2019

Код ниже будет применять верхний индекс к любому из порядковых суффиксов (st, nd, rd, th)

Public Sub MakeOrdinalSuffixesSuperscript()
' makes any of st, nd, rd, th superscripted text when preceded by a
' number and followed by a character not a number or letter

' find a (single number) followed by (two lowercaseletters) from the above
' followed by a (character that is not a letter or a number)
Const FIND_TEXT                               As String = "([0-9])([dhnrst]{2,2})([!0-9a-zA-Z])"
Dim mySearchRange                             As Word.Range

    ' there are a number of ways in which the document content can be selected
    ' this version I feel is best as it is explicit about which text story
    ' in which it is searching
    Set mySearchRange = ActiveDocument.StoryRanges(wdMainTextStory)

    With mySearchRange

        ' Set up the find object
        ' when used with a range the find object will remember the previous settings
        ' so if there is no change in what we search for the execute method
        ' can be called repeatedly without resetting all the find object parameters
        With .Find

            .ClearFormatting
            .Text = FIND_TEXT
            .Forward = True
            .Wrap = wdFindStop
            .MatchWildcards = True
            .Format = False

        End With

        Do While .Find.Execute
            ' mySearchRange is now the found text so all of the dot notations refer
            ' to mySearchRange

            ' if we didn't want to interfere with the search range we would dim a
            ' new search range variable and make a copy of the search range using
            ' the .duplicate method.

            ' Shrink the range to the two ordinal suffix characters, note the -1 for moveend
            .MoveStart unit:=wdCharacter, Count:=1
            .MoveEnd unit:=wdCharacter, Count:=-1

            ' apply superscript to the oridinal suffix characters
            .Font.Superscript = True

            ' reset the range to include the text from after mySearchRange to
            ' the end of the document
            .MoveStart unit:=wdCharacter, Count:=.Characters.Count + 1
            .End = ActiveDocument.StoryRanges(wdMainTextStory).End

        Loop

    End With

    Beep

End Sub
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...