【问题标题】:how to tell if .selection.find found anything in excel vba如何判断 .selection.find 是否在 excel vba 中找到任何内容
【发布时间】:2018-11-05 00:14:09
【问题描述】:

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

[更新]以下代码有效:

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

【问题讨论】:

  • 我假设代码被重复使用?而且它可能是“第一次”工作......不幸的是,您没有提供完整的代码,也没有解释您如何“更新”以前工作的代码。没有这些信息,没有人可以帮助您。如果您查阅网站的help center 中有关提问的信息,您会看到您需要提供minimal reproducible example,以便人们能够帮助您。
  • @CindyMeister 感谢您的评论。这次我解决了这个问题。以后我提出问题时会发布更多有用的信息。
  • @CindyMeister 我改变了我的问题。你能看看吗?谢谢。
  • 您的代码仍然无法编译 - 与 End If 匹配的 If 在哪里?

标签: excel vba ms-word find


【解决方案1】:

尝试以下方式:

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

【讨论】:

  • 谢谢。该代码运行良好。实际上,我尝试添加一些新代码以在 word 文件中的 Sheet3.Range("G2") 之后插入 Sheet2.Range("A1","B10")。但是,新部分会插入到Sheet3.Range("G2") 之前。 (对不起,我不知道如何在评论中发布代码。按 ctrl+k 将打开 Chrome 搜索框,而不是切换代码)
  • 您更新后的代码仍将Sheet2.Range("A1:B10") 放在word 文件中Sheet3.Range("G2") 之前。我修复并将更新的代码放入问题中。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-07
  • 2011-02-22
  • 1970-01-01
  • 2021-01-11
  • 1970-01-01
  • 2016-01-31
  • 1970-01-01
相关资源
最近更新 更多