word VBA 通过相互嵌套的With Selection.Find进行海量替换

180it 2019-09-25 PM 4298℃ 0条

在提取数据时,会遇到具有相似格式的内容,例如同一个word文档中出现了“(C01B35/06优先)”、(C01C11/00优先),(C01C18/00优先)……等,其存在相似的通配符格式,即"\(*优先\)",但如果直接全部替换,又有可能误删数据。
必须先将所有符合这种格式的数据找出后形成数组,然后进行批量替换,如果手动录入会非常麻烦,那么可以用到下述代码。以下以字符长度L为第二判别条件实现降噪,将需要删除的数据直接筛出,然后进行批量替换

先通过for循环和With Selection.Find 将带有上述格式的,且字符长度<=20的全部数据存储在a(0 to 1000)中。
然后在以赋值后的a(0 to 1000)作为被替换文本进行批量replace成""即可。

注:如果电脑配置不高,建议将数组a的上限调小,分批次进行,否则电脑会假死。如果假死则可通过CTRL+PAUSE BREAK(num lock 左上的按钮)暂停

Sub 替换文本()
Dim a(0 To 1000) As String
Dim search As String
Selection.HomeKey Unit:=wdStory

For i= 1 To UBound(a)
With Selection.Find
     .Text = "\(*优先\)"
     .Replacement.Text = ""
     .Forward = True
     .Wrap = wdFindStop
     .MatchWildcards = True     '使用通配符
End With
Selection.Find.Execute
search = Selection.Text
L = Len(Selection.Text)
If L <= 20 Then
a(i) = Selection.Text
End If

Next i

For i = 1 To UBound(a)
With Selection.Find

 .Text = a(i)
 .Replacement.Text = ""
 .Forward = True
 .Wrap = wdFindContinue
  .MatchWildcards = False    '不使用通配符

End With

 Selection.Find.Execute Replace:=wdReplaceAll

Next i

End Sub

本文链接:https://blog.csdn.net/weixin_44559388/article/details/87909700

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

word VBA 通过相互嵌套的With Selection.Find进行海量替换