I'm writing a macro in Word to find an open parenthesis, select from that character to the start of the paragraph, and then reformat the selected text into small caps. Fair warning, I know nothing about VBA and I hack these macros together from examples I find online.
The last part of the macro moves the cursor to the start of the next paragraph so that I can run it again. I'd like to loop it, but I haven't figured out how to set a stopping point for the loop yet.
The following macro works, but there has to be a better way to do it. This method results in a lot of screen flicker and takes forever to run.
Sub References()
'
' References Macro
'this part selects text until it finds an open parenthesis
Dim flag As Boolean
flag = True
While flag = True
Selection.MoveRight Unit:=wdCharacter, Count:=1, _
Extend:=wdExtend
'checks the last character to see if its a open parenthesis
If Strings.Right(Selection.Range.Text, 1) = "(" Then
'if it was an open parenthesis the loop flag will end
flag = False
End If
Wend
'this part reformats the text
With Selection.Font
.Name = "Times New Roman"
.Size = 12
.Bold = False
.Italic = False
.Underline = wdUnderlineNone
.UnderlineColor = wdColorAutomatic
.StrikeThrough = False
.DoubleStrikeThrough = False
.Outline = False
.SmallCaps = True
.AllCaps = False
.Color = wdColorAutomatic
.Spacing = 0
.Scaling = 100
.Position = 0
.Kerning = 1
End With
'this part moves the cursor to the beginning of the next paragraph
Selection.HomeKey Unit:=wdLine
Selection.MoveDown Unit:=wdParagraph, Count:=1
End Sub
CodePudding user response:
For example, using Find (which is way faster than testing every character):
Sub Demo()
Application.ScreenUpdating = False
Dim i As Long
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "("
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = False
End With
Do While .Find.Execute
i = i 1
.Start = .Paragraphs.First.Range.Start
.Font.SmallCaps = True
.Start = .Paragraphs.First.Range.End
Loop
End With
Application.ScreenUpdating = True
MsgBox i & " instances processed."
End Sub