我在Word中有以下代码:
Function findRanges(keyword) As Variant()
Dim foundRanges(), rngSearch As Range
Dim i, foundCount As Integer
i = 0
foundCount = 0
Set rngSearch = ActiveDocument.Range
With rngSearch.Find
Do While .Execute(FindText:=keyword, MatchWholeWord:=True, Forward:=True) = True
foundCount = foundCount + 1
rngSearch.Collapse Direction:=wdCollapseEnd
Loop
End With
ReDim foundRanges(0 To foundCount - 1)
Set rngSearch = ActiveDocument.Range
With rngSearch.Find
Do While .Execute(FindText:=keyword, MatchWholeWord:=True, Forward:=True) = True
Set foundRanges(i) = rngSearch
MsgBox "rngSearch / " & rngSearch.End
MsgBox "foundRanges / " & foundRanges(i).End
i = i + 1
rngSearch.Collapse Direction:=wdCollapseEnd
Loop
End With
For j = LBound(foundRanges) To UBound(foundRanges)
MsgBox j & "foundRanges / " & foundRanges(j).End
Next j
findRanges = foundRanges
End Function
当我使用此功能时,存储在数组“ foundRanges”中的范围是不同的(我通过其End位置对其进行检查)。但是,一旦我的find循环结束,范围就会变得完全相同(它们具有相同的End位置),而我不知道为什么。
我要做的是将每个找到的关键字的位置存储在数组中,然后将关键字更改为用户输入。
答案 0 :(得分:0)
在存储范围之前,您需要先duplicate,否则您将继续存储对相同范围的引用,并且该范围会随着您反复调用.Find()
而不断变化。
类似这样的东西:
Function findRanges(keyword, Optional SearchIn As Range) As Variant()
Dim foundRanges(), i As Integer
If SearchIn Is Nothing Then Set SearchIn = ActiveDocument.Range
Do While SearchIn.Find.Execute(FindText:=keyword, MatchWholeWord:=True, Forward:=True)
ReDim Preserve foundRanges(i)
Set foundRanges(i) = SearchIn.Duplicate
SearchIn.Collapse Direction:=wdCollapseEnd
i = i + 1
Loop
findRanges = foundRanges
End Function