VBA Word: I would like to find a phrase, select the words before it, and italicise the text -
i'm having trouble vba commands find phrase, select 1 or 2 words before it, , italicize entire thing.
i'm able use selection.find, font.italicise, , wdextend commands independently of eachother, when combine them perform task, macro crashes. help?
selection.find.clearformatting selection.find .text = "michael" .replacement.text = "michael" .forward = true .wrap = wdfindstop while .execute() = true selection.typeparagraph selection.moveleft unit:=wdword, count:=2, extend:=wdextend selection.find.replacement.font.italic = true selection.font.bold = true selection.collapse direction:=wdcollapseend loop end
the following code want. however, wrote in such way think enable best understand it.
private sub selfind() ' 08 apr 2017 dim rng range dim fnd boolean set rng = selection.range rng.find .clearformatting .execute findtext:="michael", forward:=true, _ format:=false, wrap:=wdfindstop fnd = .found end if fnd = true rng .movestart wdword, -2 .font .italic = true .bold = true end end end if end sub
start imagining characters in document strung single line, interspersed formatting codes treated characters. long string of characters called range, in code, activedocument.range
.
you can select part of document's entire range. selection.range
which, ranges, has start (the first byte) , end (the last byte. start
, end
properties of range
represented numbers, counting first byte. code creates new range object called rng. selection.range assigned new object. rng
, selection.range
identical @ point, manipulate rng
object, selection.range
not change.
the code looks "michael" in rng
object. syntax setting search perfect. used different syntax because find easier grasp. .found
property returns true if search successful. in case search range changed include found sub-range. had search been conducted in selection.range
see "michael" highlighted on screen. since search conducted in memory (on rng
object) selection.range
remains unchanged while rng
object contains word "michael".
so, going activedocument.range
, of rng
part, move start
property 2 words left. positive number move 2 words right. there no need extend
because command clear: "move start", meaning end remains is.
now rng object starts 2 word before "michael" , ends word "michael". can copy range or delete it, or modify wish. bear in mind screen still shows original selection.range
. ms word not allow assign set selection.range = rng
, there easier way realign display code has done. adding line .select
after modifying font (before outer end with
), modified rng
become selection.
Comments
Post a Comment