我已经手动完成了此操作,我想将 ZXZ 的每个实例替换为从 1 一直到 Word 文档中最后一次出现的 ZXZ 的序列号。
基本上,我想要实现的是在特定的Word文档中运行Word VBA宏,其中VBA宏从文件顶部开始搜索,查找每个出现的ZXZ,将第一次出现的ZXZ替换为“1”然后依次出现下一个“2”,直到在 Word 文档中找到最后一个 ZXZ。
示例 Word 文档可能包含:
元素ZXZ
元素ZXZ
...
元素ZXZ
运行 vba word 宏后,我想得到:
元素1
元素2
...
25号元素
我已经用这段代码完成了此操作,但我想做“while”循环或查找每次出现的 ZXZ 并将其替换为从“1”开始的连续数字
Sub my_prov_MDList()
'
' my_prov_MDList Macro
'
'
Selection.MoveUp Unit:=wdScreen, Count:=7
Selection.HomeKey Unit:=wdLine
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "ZXZ"
.Replacement.Text = "1"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
With Selection
If .Find.Forward = True Then
.Collapse Direction:=wdCollapseStart
Else
.Collapse Direction:=wdCollapseEnd
End If
.Find.Execute Replace:=wdReplaceOne
If .Find.Forward = True Then
.Collapse Direction:=wdCollapseEnd
Else
.Collapse Direction:=wdCollapseStart
End If
.Find.Execute
End With
With Selection.Find
.Text = "ZXZ"
.Replacement.Text = "2"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
With Selection
If .Find.Forward = True Then
.Collapse Direction:=wdCollapseStart
Else
.Collapse Direction:=wdCollapseEnd
End If
.Find.Execute Replace:=wdReplaceOne
If .Find.Forward = True Then
.Collapse Direction:=wdCollapseEnd
Else
.Collapse Direction:=wdCollapseStart
End If
.Find.Execute
End With
''''我基本上一直重复上面的代码,直到达到 25,这通常是每个文档中存在的 ZXZ 实例的数量。
效率更高:
Sub Demo()
Application.ScreenUpdating = False
Dim i As Long
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "ZXZ"
.Replacement.Text = ""
.Format = False
.Forward = True
.Wrap = wdFindStop
.MatchWildcards = True
.Execute
End With
Do While .Find.Found
i = i + 1
.Text = i
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
Application.ScreenUpdating = True
MsgBox i & " instances found."
End Sub
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)