我有一个VBA宏(Word2010)脚本来突出显示所有斜体文本。但是当在大文件中执行时,说出一个超过10页的文档,Word就会崩溃。 为此,我使用了以下代码。
Sub Italics_Highlight()
'
' test_italics_highlight_ Macro
'
'
Application.ScreenUpdating = False
Dim myString As Word.Range
Set myString = ActiveDocument.Content
With myString.Find
.ClearFormatting
.Text = ""
.Font.Italic = True
While .Execute
myString.HighlightColorIndex = wdTurquoise
myString.Collapse wdCollapseEnd
Wend
End With
MsgBox "Thank you!"
End Sub
你能帮忙克服这个问题吗?感谢您的帮助。
答案 0 :(得分:1)
您的错误说明看起来像您的代码永远在运行但未完成。
您可能希望在DoEvents
循环中添加While
,以便在运行代码时保持Word的响应速度。
With myString.Find
.ClearFormatting
.Text = ""
.Font.Italic = True
While .Execute
DoEvents 'keeps Word responsive
myString.HighlightColorIndex = wdTurquoise
myString.Collapse wdCollapseEnd
Wend
End With
我不确定您的代码是否会停止。循环可能不会在文档的末尾停止,而是从头开始重新开始,因此总是会一次又一次地找到斜体,永远循环。
因此,您可能需要将.Wrap = wdFindStop
设置为在文档末尾停止
请参阅Find.Wrap Property (Word)。
With myString.Find
.ClearFormatting
.Text = ""
.Font.Italic = True
.Wrap = wdFindStop 'stop at the end of the document
While .Execute
DoEvents 'keeps Word responsive
myString.HighlightColorIndex = wdTurquoise
myString.Collapse wdCollapseEnd
Wend
End With
答案 1 :(得分:0)
你不需要在每个"发现"并应用突出显示。您可以在查找/替换中执行此操作:
Sub testInfiniteLoop()
Dim myString As word.Range
Set myString = ActiveDocument.content
Options.DefaultHighlightColorIndex = wdTurquoise
With myString.Find
.ClearFormatting
.Text = ""
.Font.Italic = True
.Replacement.Text = ""
.Replacement.Highlight = wdTurquoise
.wrap = wdFindStop 'stop at the end of the document
.Execute Replace:=wdReplaceAll
End With
End Sub
答案 2 :(得分:0)
以下代码不仅会突出显示,还会恢复以前生效的任何突出显示设置:
Sub Italics_Highlight()
Application.ScreenUpdating = False
Dim i As Long: i = Options.DefaultHighlightColorIndex
Options.DefaultHighlightColorIndex = wdTurquoise
With ActiveDocument.Content.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = ""
.Replacement.Text = "^&"
.Replacement.Highlight = True
.Format = True
.Font.Italic = True
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
Options.DefaultHighlightColorIndex = i
Application.ScreenUpdating = True
MsgBox "Done!"
End Sub
如您所见,您也不需要:
Dim myString As Word.Range
Set myString = ActiveDocument.Content