【问题标题】:VBA search for string in document and check its colorVBA 在文档中搜索字符串并检查其颜色
【发布时间】:2014-01-13 10:10:55
【问题描述】:

我尝试创建一个函数来搜索文档中的字符串并检查字符串中红色的第一个字符是什么。

例如,我知道我的文档包含字符串“面包水果汁桃酒”。想象一下粗体文本是红色的。我希望函数返回 int 19(第一个红色字符 - p)。

 Function check(stringToCheck As String) As Integer
Dim oRng As Word.Range
Set oRng = ActiveDocument.Content

With oRng.Find
    ' to ensure that unwanted formats aren't included as criteria
    .ClearFormatting
    'You don't care what the text is
    .Text = stringToCheck
    'Loop for each match and set a color
    While .Execute
        MsgBox (oRng.Text)
        For i = 1 To 40
'take the Nth char of the string an check if it's red
'the following msgBox is working
MsgBox (Mid(oRng, i, 1))
If Mid(Orng, i, 1).Font.Color = wdColorRed Then
'the following msgBox is not working which means the error is in the last line.
MsgBox ("made it")
check = i
Exit Function
End If
Next i

    Wend

End With


End Function

每次我尝试调用该函数时都会出现错误“运行时错误 424 - 需要对象”。

我添加了一些 msgboxes 以查看函数何时中断并在该位置添加了注释。

有什么问题?我该如何解决?

【问题讨论】:

    标签: string vba search colors ms-word


    【解决方案1】:

    第一件事:在模块的开头使用Option Explicit。您会很快发现您的代码存在编译问题。

    您的意思是使用oRng 还是myRange?这应该是一致的。

    一旦你这样做了......

    Mid(myRange, i, 1) 返回一个字符串,而不是一个对象。

    您可能想改用If oRng.Characters(1).Font.Color = wdColorRed Then

    这是您修改后正确返回的代码:

    Function check(stringToCheck As String) As Integer
    Dim oRng As Word.Range
    Set oRng = ActiveDocument.Content
    Dim i As Integer
    With oRng.Find
        ' to ensure that unwanted formats aren't included as criteria
        .ClearFormatting
        'You don't care what the text is
        .Text = stringToCheck
        'Loop for each match and set a color
        While .Execute
            MsgBox (oRng.Text)
            For i = 1 To 40
    'take the Nth char of the string an check if it's red
    'the following msgBox is working
    MsgBox oRng.Characters(i)
    If oRng.Characters(i).Font.Color = wdColorRed Then
    'the following msgBox is not working which means the error is in the last line.
    MsgBox ("made it")
    check = i
    Exit Function
    End If
    Next i
    
        Wend
    
    End With
    
    
    End Function
    

    【讨论】:

    • @Amos 我已经完成了我的回答。 Range 对象有一个 Characters 属性,可以让你做你想做的事。
    • 哇,谢谢!但我认为您的意思是字符(i)而不是字符(1)。
    • @Amos 啊,是的,对不起。此外,您可能需要考虑将循环从 1 To 40 调整为 1 To Len(Characters)
    猜你喜欢
    • 2018-02-14
    • 2021-03-26
    • 2013-08-02
    • 1970-01-01
    • 2015-01-12
    • 2014-12-30
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    相关资源
    最近更新 更多