Jezza
Jezza

Reputation: 3

Word VBA - find a text string where a one word (not all words in string) have a particular style or format

I was trying to construct some code to search for text where one word within the text is a particular format or style. For example, I would like to search for the text "Hello world, all is good" but only hit instances where the word "all" is in bold.

I thought about searching for the first few words "Hello world, "; collapsing the selection, searching the next three characters forward for the word "all" in bold; collapsing the selection (if true) then searching the next bit for the words " is good". This would result in identifying the whole phrase with the bold word but it seems really inefficient and not very flexible. Also, to then select the whole sentence, I have to write code to move the selection back to the start and extend the selection forward. Then I need to reset the search to continue forward from that position.

Is there some easy/easier/more elegant way to search for a string where only one word within the string has specific properties like bold? I specifically want the search to ignore instances of the phrase where the relevant word is not in bold.

I have spent a few hours searching google and stackflow and can't find anything on this.

I haven't posted code because I am not very good at writing the code, and I really want to understand if there is a flexible/elegant way of doing what I want. The inflexible root I've explained above is so inflexible I'm reluctant to bother coding something.

Thanks Jeremy

Upvotes: 0

Views: 466

Answers (1)

Sam
Sam

Reputation: 381

The method I would use is to search for the string and, if found, then search the string for the word. Here is an example.

Sub Demo()
    Dim StringRange As Range
    Dim MatchFound  As Boolean
    
    With ActiveDocument.Range.Find
        ' The string to find
        .Text = "Hello world, all is good"
        
        ' Search the document
        Do While .Execute
            ' Capture the string
            Set StringRange = .Parent.Duplicate
            
            With .Parent.Duplicate.Find
                ' The word to find
                .Text = "all"
                .Font.Bold = True
                
                ' Search the string
                If .Execute Then
                    MatchFound = True
                    StringRange.Select
                    
                    If MsgBox("Match found. Continue searching?", vbQuestion + vbYesNo) = vbNo Then
                        Exit Sub
                    End If
                End If
            End With
        Loop
        
        If MatchFound Then
            MsgBox "Finished searching document", vbInformation
        Else
            MsgBox "No match found", vbInformation
        End If
    End With
End Sub

Upvotes: 0

Related Questions