我需要在文档的每个页面上搜索一个名称,然后如果找到该名称,我会搜索另一个单词来替换它(已经在同一页面上)! 我尝试了很多不同的代码,但没有找到有效的结果
Sub Find()
Call SearchAndMark("Article : KR", "DéfautsKR")
Call SearchAndMark("Article : IP", "DéfautsIP")
End Sub
Sub SearchAndMark(searchString As String, markText As String)
Dim CurrentPage As Integer
Dim LastPage As Integer
Selection.GoTo What:=wdGoToPage, Which:=wdGoToFirst
CurrentPage = Selection.Information(wdActiveEndAdjustedPageNumber)
LastPage = Selection.Information(wdNumberOfPagesInDocument)
While (CurrentPage < LastPage)
Selection.Find.Forward = True
Selection.Find.Text = searchString
Selection.Find.Execute
If Selection.Find.Found Then
With Selection.Find
.Text = "Défauts"
.Replacement.Text = markText
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=wdReplaceOne
End With
Else
CurrentPage = LastPage
End If
CurrentPage = Selection.Information(wdActiveEndAdjustedPageNumber)
Wend
End Sub
答案 0 :(得分:0)
问题是由以下部分代码引起的:
'If searchString is not found, set the CurrentPage to LastPage
'This should cause the loop to end
CurrentPage = LastPage
End If
'Reset the current page to the end page for the end of the active selection
'This will run even if searchString was not found, preventing the loop from ending
CurrentPage = Selection.Information(wdActiveEndAdjustedPageNumber)
Wend
下面的行需要移动到If语句的“True”部分: CurrentPage = Selection.Information(wdActiveEndAdjustedPageNumber)
所以我们最终得到:
Sub SearchAndMark(searchString As String, markText As String)
Dim CurrentPage As Integer
Dim LastPage As Integer
Selection.GoTo What:=wdGoToPage, Which:=wdGoToFirst
CurrentPage = Selection.Information(wdActiveEndAdjustedPageNumber)
LastPage = Selection.Information(wdNumberOfPagesInDocument)
While (CurrentPage < LastPage)
Selection.Find.Forward = True
Selection.Find.Text = searchString
Selection.Find.Execute
If Selection.Find.Found Then
With Selection.Find
.Text = "Défauts"
.Replacement.Text = markText
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=wdReplaceOne
End With
CurrentPage = Selection.Information(wdActiveEndAdjustedPageNumber)
Else
CurrentPage = LastPage
End If
Wend
End Sub
还值得注意的是,代码不是在特定页面内搜索。它找到了searchString的一个实例,如果找到它,它会搜索下一个“Défauts”实例,并用markText替换它。这意味着如果“Défauts”位于同一页面上的searchString之上,则不会被替换。如果“Défauts”出现在下一页上,它将被替换。这可能是你需要的,但它与你上面描述的不完全相同。