在搜索和替换Word VBA中使用宏

时间:2018-08-07 18:21:47

标签: vba replace ms-word full-text-search

我正在尝试开发一段代码,该代码将从文本中提取某些名称(Kennedy,Nixon等),并用标记(@ Kennedy,@ Nixon)替换它们。由于时间的限制,我想使用数组。我尝试了多个示例,但是没有运气。我能找到的最佳模型如下:

Sub Macro1()

Dim i As Variant
Dim NameOrig As Variant
Dim NameSub As Variant
NameOrig = Array("McGee", "NIXON", "KENNEDY")
NameSub = Array("@McGee", "@NIXON", "@KENNEDY")
With ActiveDocument.Find
  .ClearFormatting
  .Replacement.ClearFormatting
  .Forward = True
  .Wrap = wdFindContinue
  .Format = True
  For i = 1 To UBound(NameOrig)
    .Text = NameOrig(i)
    .Replacement.Text = NameSub(i)
    .Execute Replace:=wdReplaceAll
  Next
End With
End Sub

最终,我最终遇到运行时错误“ 438”:对象不支持此属性或方法。有没有办法来解决这个问题?或者,还有另一段实际起作用的代码。

1 个答案:

答案 0 :(得分:3)

您需要使用“ ActiveDocument.Content.Find”或“ ActiveDocument.Range.Find”。您也不需要'Dim NameSub As Variant','NameSub = Array(“ @ McGee”,“ @ NIXON”,“ @ KENNEDY”)'或'.Replacement.Text = NameSub(i)'。最后,除非您设置了“ Option Base 1”,否则如果您没有从0开始循环,那么您将错过第一项。试试:

Sub Macro1()
Dim i As Long, NameOrig As Variant
NameOrig = Array("McGee", "NIXON", "KENNEDY")
With ActiveDocument.Range.Find
  .ClearFormatting
  .Replacement.ClearFormatting
  .Forward = True
  .Wrap = wdFindContinue
  .Format = True
  .Replacement.Text = "@^&"
  For i = 0 To UBound(NameOrig)
    .Text = NameOrig(i)
    .Execute Replace:=wdReplaceAll
  Next
End With
End Sub