VBA为什么无法正常运行我的代码行?

时间:2019-05-08 08:13:07

标签: vba debugging ms-word

我编写了一个“简单”代码来查找Word文件中一定长度的引号(我最终希望使用其他子格式设置引号)。这些部分都可以单独正常运行,但是现在的搜索基本上是跳过应该在文本中找到的字符串,并且显然会使代码行混乱。

我尝试了中断模式并观察了Selection的值,这很奇怪:它不断查找搜索参数的下一个实例(在文档中进行选择并更改Selection的值),当我运行每行代码时,包括With Selection.Find之前的.Execute内!

Sub FindQuotesTest()

Dim quotevar As String, loopvar As Boolean

Findquote:
loopvar = False 'Doesn't seem necessary, added to try debugging
Selection.Collapse 'Not sure if this is necessary
Selection.Find.ClearFormatting
With Selection.Find
        .MatchWildcards = True
        .Text = ChrW(8220) & "*" & ChrW(8221) 'Any amount of text between an opening and a closing curly double quotation marks.
        .Forward = True
        .Wrap = wdFindStop 'To avoid a crash when reaching the end of the document
        End With
Selection.Find.Execute

loopvar = Selection.Find.Execute

With Selection
    .MoveStartWhile Cset:=ChrW(8220) 'Removes the opening quotation mark from selection
    .MoveEndWhile Cset:=ChrW(8221), Count:=wdBackward 'Removes the closing quotation mark from selection
End With 'I need this for the further formatting and to count the text string

quotevar = Selection.Range

If Len(quotevar) < 157 Then 'Repeats the search if the quote isn't long enough.
If loopvar = True Then GoTo Findquote 'Prevents infinite loop when reaching the end of the document by relying on wdFindstop
End If

End Sub

在中断模式下,它应该一次在双引号中找到一个字符串,只有在到达GoTo循环时才转到下一个字符串,直到到达指定长度的字符串为止(应该遍历.Find几次)。 当我再次运行宏时,它应该找到长引号的下一个实例(似乎是每隔一秒查找一次。在我之前的尝试中,宏只会运行一次,而在再次运行时找不到下一个实例,这段代码不会发生这种情况。

穿越时间的中断模式的怪异行为使我离开了这里,所以我很茫然。任何帮助将不胜感激!干杯。

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "“*”"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchWildcards = True
    .Execute
  End With
  Do While .Find.Found
    If .End - .Start > 159 Then
      With .Duplicate
        .Start = .Start + 1
        .End = .End - 1
        'Process string here
      End With
    End If
    .Collapse wdCollapseEnd
    .Find.Execute
  Loop
End With
Application.ScreenUpdating = True
End Sub

您将找到比您自己的代码快得多的代码。 FWIW,“ *”中的开始和结束引号分别为ASCII 147和148-不需要ChrW等效项。