Forum Discussion
Selecting an entire line containing a specific word
I wished to know if there is any possible way to automatically select an entire line where a specific word occurs? If there is, how can we do it for multiple (all) occurrences as well?
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 With
Replace the wdRed with whatever colour you want.
- roshanbangeraCopper Contributor
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?
- roshanbangeraCopper ContributorBasically I wish to change the font color of the entire line in which a specific word is found. Thankyou