excel - 使用循环在 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
解决方案
问题在于您设置 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
推荐阅读
- python - 为什么 pycharm 中的“in”运算符让我失望了?
- react-native - 在堆栈/屏幕之间传递参数
- node.js - NodeJS:数组不保存
- visual-studio - Power BI 视觉对象不会绘图或显示我添加的格式选项
- javascript - 为什么 jQuery(document).on('click... 不注册对特定 div 的点击?
- mysql - mysql sum group by month and date using a contract start and end date
- google-sheets - 如果满足单元格值的条件,则返回所有对行/列的列表
- node.js - 在 Docker 容器中开发 Node.js 应用程序
- java - GlassFish 无法识别特定的 servlet
- intellij-idea - 想法 - 保存差异结果