如何判断.selection.find是否在excel vba中找到了任何内容

时间:2018-11-05 00:14:10

标签: excel vba ms-word find

我可以使用此代码在用户指定的单词文件中找到一个句子,然后在该句子之后插入文本。问题是如果单词文件中不存在预期的句子,则文本将插入到单词文件的开头。我需要的是,如果找不到期望的句子,请转到错误处理程序。如何修改代码?

[更新]以下代码有效:

Dim WordApp As Object, WordDoc As Object
Dim FullName As String: FullName = Sheet5.Cells(7, 5).Value

Set WordApp = New Word.Application

With WordApp
    .Visible = True

    Set WordDoc = .Documents.Open(FullName)

    .ActiveDocument.Select
    With .Selection
        With .Find
            .ClearFormatting
            .MatchWholeWord = True
            .MatchCase = False
            .Text = "There is one electric heater."
            .Execute
        End With
        If .Find.Found Then
        .Collapse Direction:=wdCollapseStart
        .TypeParagraph
        .ParagraphFormat.Alignment = wdAlignParagraphLeft
        .MoveEnd wdLine, 1
        Sheet3.Range("G2").Copy
        .PasteExcelTable False, False, False
        Sheet2.Range("A1", "B10").Copy
        .PasteExcelTable False, False, False
        Else
        MsgBox "No electric heater reference found.", vbExclamation
        End If
    End With
    .Activate
End With

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

Dim WordApp As Object, WordDoc As Object, WordRng As Object
Dim strFlNm As String: strFlNm = Sheet5.Range("D6").Value
Set WordApp = CreateObject("Word.Application")
With WordApp
  .Visible = True
  Set WordDoc = .Documents.Open(strFlNm)
  With WordDoc.Range
    With .Find
      .ClearFormatting
      .MatchWholeWord = True
      .MatchCase = False
      .Text = "There is one electric heater."
      .Execute
    End With
    If .Find.Found = True Then
      .InsertAfter vbCr
      .Collapse 0 ' wdCollapseEnd
      .ParagraphFormat.Alignment = 0 'wdAlignParagraphLeft
      Sheet3.Range("G2").Copy
      .PasteExcelTable False, False, False
      .InsertAfter vbCr
      Sheet2.Range("A1:B10").Copy
      .Collapse 0 ' wdCollapseEnd
      .PasteExcelTable False, False, False
    Else
      MsgBox "No electric heater reference found", vbExclamation
    End If
  End With
  .Activate
End With