PDA

View Full Version : [SOLVED:] Find text between and color it



Grrr1337
03-03-2018, 04:30 PM
Hello everyone,
I have this content in my word document:

This is some text.. so this [[particular text]] must be put in red.
And theres [[another text that must be put in red]] and some more text. Also theres [[this text]] that must be put in red.

However the sentences in my doc do not have assigned color, so I'm asking if anyone could write a Sub to put a red colour on all text which is between [[ and ]], like in the above ^^.

This Sub does the job, but only for the first pair of [[ .. ]], and I'm wondering how to iterate over all the content.

Sub ColourWithin() 'https://answers.microsoft.com/en-us/msoffice/forum/msoffice_word-msoffice_custom-mso_2010/how-to-use-vba-to-copy-text-between-two-specified/768a1b76-f79d-46cf-aab4-e6bacf761992
Dim lngStart As Long
Dim lngEnd As Long
Dim docNew As Document
Selection.HomeKey Unit:=wdStory
With Selection.Find
.ClearFormatting
.Wrap = wdFindStop
.MatchCase = False
.Text = "[["
If .Execute = False Then
MsgBox "'Summary' not found.", vbExclamation
Exit Sub
End If
Selection.Collapse Direction:=wdCollapseEnd
lngStart = Selection.End
.Text = "]]"
If .Execute = False Then
MsgBox "']]' not found.", vbExclamation
Exit Sub
End If
lngEnd = Selection.Start
End With
ActiveDocument.Range(lngStart, lngEnd).Font.ColorIndex = wdRed
End Sub

mana
03-03-2018, 10:25 PM
Option Explicit

Sub test()
Dim r As Range

Set r = ActiveDocument.Range

With r.Find
.MatchWildcards = True

.Text = "\[\[*\]\]"
.Replacement.Font.Color = wdColorRed
.Execute Replace:=wdReplaceAll

.Text = "\[\["
.Replacement.Font.Color = wdColorAutomatic
.Execute Replace:=wdReplaceAll

.Text = "\]\]"
.Execute Replace:=wdReplaceAll

End With

End Sub



マナ

Grrr1337
03-04-2018, 04:00 AM
Thank you, mana
Worked like a charm! :)