Word VBA:查找一串文本并将其所有实例更改为首字母大写

Word VBA: Find a string of text and change all instances of it to title case

我正在尝试编写一个宏来将“第 1 节”、“第 2 节”等的大小写更改为标题大小写,因此它们都显示为“第 1 节”等。我已经改编 Variatus' very helpful code 这里:

    Dim Rng As Range
    Dim Fnd As Boolean

Set Rng = Selection.Range
With Rng.Find
    .ClearFormatting
    .Execute FindText:="section [0-9]", Forward:=True, _
             Format:=False, Wrap:=wdFindContinue, MatchWildcards:=True
    Fnd = .Found
End With

If Fnd = True Then
    Rng.Case = wdNextCase
End If

我遇到的问题是它一次只更改一个实例。理想情况下,它会通过一次按键更改所有实例的大小写。

作为奖励,我还希望将大小写更改注册为跟踪更改。当我使用跟踪更改时,我不能用 section ([0-9])Section 做一个简单的替换文本宏,因为跟踪的错误使其成为“1Section”、“2Section”等。这是这是必不可少的,但会是一个非常好的奖励。 .Case 函数没有被跟踪,.Font 只有 .AllCaps.

的选项

也许有一种方法可以找到section [0-9],将光标移动到单词的开头和select第一个字母,设置.Font.AllCaps = True,循环直到没有section [0-9] 的更多实例?只是一个想法,但这远远超出了我目前的宏观能力。现在最主要的是让上面的代码应用于 section [0-9].

的所有实例

干杯!

尝试:

Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "section [0-9]"
    .Replacement.Text = ""
    .Format = False
    .Forward = True
    .Wrap = wdFindStop
    .MatchWildcards = True
  End With
  Do While .Find.Execute
    .Characters.First.Text = "S"
    .Collapse wdCollapseEnd
  Loop
End With
Application.ScreenUpdating = True
End Sub