【问题标题】:Word VBA - find a text string where a one word (not all words in string) have a particular style or formatWord VBA - 查找一个文本字符串,其中一个单词(不是字符串中的所有单词)具有特定的样式或格式
【发布时间】:2024-01-15 15:33:02
【问题描述】:

我试图构建一些代码来搜索文本中的一个单词是特定格式或样式的文本。例如,我想搜索文本“Hello world, all is good”,但只搜索单词“all”为粗体的实例。

我想搜索前几个单词“Hello world,”;折叠选择,向前搜索接下来的三个字符以查找粗体字“all”;折叠选择(如果为真),然后在下一位搜索单词“很好”。这将导致用粗体字识别整个短语,但它似乎真的效率低下并且不是很灵活。此外,要选择整个句子,我必须编写代码将选择移回开始并向前扩展选择。然后我需要重置搜索以从该位置继续前进。

是否有一些简单/更容易/更优雅的方法来搜索字符串中只有一个单词具有特定属性(如粗体)的字符串?我特别希望搜索忽略相关单词不是粗体的短语实例。

我花了几个小时搜索 google 和 stackflow,但在这方面找不到任何东西。

我没有发布代码,因为我不太擅长编写代码,我真的很想了解是否有一种灵活/优雅的方式来做我想做的事。我上面解释的不灵活的根太不灵活了,我不愿意费心编写代码。

谢谢 杰里米

【问题讨论】:

    标签: replace ms-word


    【解决方案1】:

    我将使用的方法是搜索字符串,如果找到,然后在字符串中搜索单词。这是一个例子。

    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
    

    【讨论】:

    • 哇。太感谢了。这正是我想做的。你这样写代码真是太慷慨了。谢谢你。我很惊讶这个问题没有更频繁地出现。再次感谢您。这绝对是完美的。
    最近更新 更多