PDA

View Full Version : VBA code; find a specific string,select the entire line the string is in,&then format



kbishop94
11-13-2019, 10:38 AM
I know my request is probably straight forward and a relatively simple one. I have googled and found different pieces of code trying to get this to work, and although some code works and does what I am wanting it to do, I cant seem to put everything together to get it all to work together.

First, this is what I am wanting the code to do:

1. find a specific string in the document (in my example I am searching for the use of the word "sub" (and find ALL uses of the word at that.)
2. select the entire line that the string is located in
3. change the format of the entire line (in my example I am changing the color of the font to a bright blue color)

The code I have right now is a hodge-podge mess of different actions that doesnt work... it DOES, however, find the word "sub"... but it only finds first one found... also, it DOES change the font color, but just the one word and not the entire line.

So I'm giving up playing with this trying to get it to work, and, at the expense of embarrassing myself, I'm now asking for help here. lol

Thanks for any help anyone can offer!



Sub aFindPriSub()


Dim Rng As Range
Dim Fnd As Boolean

Selection.WholeStory

Set Rng = Selection.Range


With Rng.Find

.ClearFormatting
.Execute FindText:="Sub", Forward:=True, _
Format:=False, Wrap:=wdFindStop
Fnd = .Found
End With


If Fnd = True Then

MsgBox Rng

With Rng

.MoveStart wdWord, -2

Selection.HomeKey Unit:=wdLine
Selection.EndKey Unit:=wdLine, Extend:=wdExtend

With .Font
.Italic = False
.Bold = True
.TextColor = RGB(0, 176, 240)

Selection.HomeKey Unit:=wdLine
Selection.EndKey Unit:=wdLine, Extend:=wdExtend

Selection.Find.Execute Replace:=wdReplaceAll
End With
End With
End If
End Sub

gmayor
11-14-2019, 02:21 AM
There are no 'lines' in a Word document. Lines are created by formatting text to the margins and if you select such a line and reformat it, the chances are that it will occupy a different space to that it previously occupied. In the context of this I would hope by 'line' that you mean paragraph, in which case it is relatively straightforward


Sub aFindPriSub()Dim Rng As Range
Set Rng = ActiveDocument.Range
With Rng.Find
.ClearFormatting
Do While .Execute(findText:="Sub", Forward:=True, _
Format:=False, Wrap:=wdFindStop)
With Rng
.Start = Rng.Paragraphs(1).Range.Start
.End = Rng.Paragraphs(1).Range.End - 1
With .Font
.Italic = False
.Bold = True
.TextColor = RGB(0, 176, 240)
End With
.Collapse 0
End With
Loop
End With
Set Rng = Nothing
End Sub