当没有匹配的格式部分时,range.find方法不返回任何内容

时间:2016-05-19 11:00:50

标签: excel vba excel-vba word-vba

下面的功能旨在将文本作为word文档的阶段图的第一部分。 Pharagraphs作为范围传递给函数。

Private Function GetFirstBoldPartofAPharagraph(rngPharagraph) As String
    With rngPharagraph.Find
        .ClearFormatting
        .Font.Bold = True
        .Execute Format:=True
    End With

   rngPharagraph.Select

   GetFirstBoldPartofAPharagraph = rngPharagraph.Text

   Set rng = Nothing
End Function

此处rngPharagraph来自myRangelngPar是word文档的法律数字)

Set myRange = objDoc.Paragraphs(lngPar).Range

此代码将在Excel工作表中执行。问题是,如果有一个粗体部分,它会找到并rngPharagraph.Text得到那个部分;但是如果没有粗体部分rngPharagraph.text则会返回所有的法线而不是返回nothing

1 个答案:

答案 0 :(得分:3)

检查Find对象结果及其Found属性:

Private Function GetFirstBoldPartofAPharagraph(rngPharagraph As Range) As String
    With rngPharagraph.Find
        .ClearFormatting
        .Font.Bold = True
        .Execute Format:=True
    End With

    If rngPharagraph.Find.Found Then
        rngPharagraph.Select
        GetFirstBoldPartofAPharagraph = rngPharagraph.Text
    End If
End Function