VBA运行时错误5941搜索空白字段

时间:2018-10-11 17:15:38

标签: vba ms-word word-vba

我正在尝试编写一个宏,以查找和标记指定文本选择中的所有空白DOCPROPERTY字段。当我尝试运行宏时,它将使用文本标记某些必填字段,但不会标记其他字段。宏然后因运行时错误5941而失败。我感觉到它与循环如何计数以及如何在空白字段中循环有关,但是我无法通过任何研究来确定修复程序。有人有什么想法吗?

 Sub RemoveFieldCodes()

'Moves to start of doc and selects text block
    Selection.HomeKey Unit:=wdStory
    Selection.HomeKey Unit:=wdStory
    Selection.MoveDown Unit:=wdLine, Count:=2
    Selection.MoveDown Unit:=wdParagraph, Count:=6, Extend:=wdExtend

'Finds blank fields and appends text to end
Dim i As Long
 With Selection 
     For i = Selection.Fields.Count To 1 Step -1
     If .Fields(i).Type = wdFieldDocProperty And .Result = "" Then 
            .Fields(i).Select
            Selection.EndKey Unit:=wdLine
            Selection.TypeText Text:="BLANK"
            End If
         Next i
     End With

1 个答案:

答案 0 :(得分:0)

您应该向后浏览整个集合;否则可能会遗漏连续的空格。试试:

Sub Demo()
Application.ScreenUpdating = False
Dim i As Long, Rng As Range
With ActiveDocument
  For i = .Fields.Count To 1 Step -1
    With .Fields(i)
      If .Type = wdFieldDocProperty Then
        If .Result = " " Then
          Set Rng = .Result
          .Delete
          Rng.Text = "BLANK"
        End If
      End If
    End With
  Next
End With
Application.ScreenUpdating = True
End Sub

目前尚不清楚为什么使用'Selection.EndKey Unit:= wdLine',因此,如果:

          Rng.Text = "BLANK"

还不够,请尝试将其替换为:

          With Rng
            .End = .Paragraphs(1).Range.End - 1
            .Text = "BLANK"
          End With