Forum Discussion
Selecting an entire line containing a specific word
- Feb 19, 2024
roshanbangera Use the following code
Dim strWord As String Dim rngFound As Range strWord = InputBox("Insert the word to be found", "Word Finder") Selection.HomeKey wdStory With Selection.Find Do While .Execute(FindText:=strWord, Forward:=True, MatchWholeWord:=True, _ MatchWildcards:=False, Wrap:=wdFindStop, MatchCase:=True) = True Set rngFound = Selection.Bookmarks("\line").Range.Duplicate Selection.Collapse wdCollapseEnd rngFound.Font.ColorIndex = wdRed Loop End WithReplace the wdRed with whatever colour you want.
Could select the line for the first occurrence only using macro
Using the following code:
***************************
Sub SelectEntireLineWithWord()
Dim searchText As String
Dim foundRange As Range
searchText = InputBox("Enter the word you want to find:", "Find Word and Select Line")
If searchText <> "" Then
Set foundRange = ActiveDocument.Range
With foundRange.Find
.Text = searchText
.Execute
If .Found Then
foundRange.Expand Unit:=wdParagraph
foundRange.Select
Else
MsgBox "Word not found.", vbExclamation
End If
End With
End If
End Sub
******************
But I am failing to do it for all the occurrences! ![]()
roshanbangera You can only select one at a time. However what is it that you want to do with each line of text that contains that word?
- roshanbangeraFeb 19, 2024Copper ContributorBasically I wish to change the font color of the entire line in which a specific word is found. Thankyou
- Feb 19, 2024
roshanbangera Use the following code
Dim strWord As String Dim rngFound As Range strWord = InputBox("Insert the word to be found", "Word Finder") Selection.HomeKey wdStory With Selection.Find Do While .Execute(FindText:=strWord, Forward:=True, MatchWholeWord:=True, _ MatchWildcards:=False, Wrap:=wdFindStop, MatchCase:=True) = True Set rngFound = Selection.Bookmarks("\line").Range.Duplicate Selection.Collapse wdCollapseEnd rngFound.Font.ColorIndex = wdRed Loop End WithReplace the wdRed with whatever colour you want.
- roshanbangeraFeb 19, 2024Copper ContributorAwesome! Thannks Doug_Robbins_Word_MVP