首页 > 解决方案 > 使用循环在 Word Doc VBA 中查找单词的问题

问题描述

我在一列中有一个动态的搜索词列表。我想打开一个 word 文档,然后拉回任何找到的单词。出于某种原因,在找到第一个匹配项后,它会继续执行代码并且不再拉回任何匹配项。它应该拉回 6 个单词,但它只拉回了我的动态列表中的第一个单词。有什么建议么?这是我的代码:

Sub SearchWord()
Dim odoc As Document
Dim path As String
Dim rng As Word.Range
path = "*MYFILEPATH*"

Dim DS As Worksheet
Dim SS As Worksheet
Set DS = Sheets("Report")
Set SS = Sheets("Search Index")

    With SS
        SSlastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
    End With

    With DS
        dslastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With


Set odoc = Documents.Open(Filename:=path)
Set rng = odoc.Content


For J = 2 To SSlastRow
    sText = SS.Range("B" & J).Value

    With rng.Find
        .MatchCase = False
        .Text = sText
    End With
    rng.Find.Execute
    If rng.Find.found = True Then
        DS.Range("Q" & 2).Value = DS.Range("Q" & 2).Value & sText & ";" & " "
    Else
        DS.Range("Q" & 2).Value = DS.Range("Q" & 2).Value
    End If
Next J

odoc.Close wdDoNotSaveChanges
End Sub

标签: excelvbams-word

解决方案


问题在于您设置 rng 的位置 - 您不需要。您的代码也可以通过其他方式进行简化。尝试:

Sub SearchWord()
Dim oDoc As Word.Document
Dim path As String
path = "*MYFILEPATH*"

Dim DS As Worksheet, SS As Worksheet
Dim SSlastRow As Long, DSlastRow As Long, J As Long
Set DS = Sheets("Report")
Set SS = Sheets("Search Index")

SSlastRow = SS.Cells(SS.Rows.Count, "B").End(xlUp).Row
DSlastRow = DS.Cells(DS.Rows.Count, "A").End(xlUp).Row

Set oDoc = Documents.Open(FileName:=path, AddToRecentFiles:=False)

For J = 2 To SSlastRow
    sText = SS.Range("B" & J).Value
    With oDoc.Range.Find
        .MatchCase = False
        .Text = sText
        .Execute
        If .Found = True Then DS.Range("Q" & 2).Value = DS.Range("Q" & 2).Value & sText & "; "
    End With
Next J

oDoc.Close False
End Sub

推荐阅读