简体   繁体   English

如何在 MS Word 宏中结束 Do 循环

[英]How to end a Do Loop in an MS Word macro

I've made a macro to change the header color of a document, but when hitting the end of the document - or if there's no remaining header - I'm getting an error.我制作了一个宏来更改文档的标题颜色,但是当到达文档末尾时 - 或者如果没有剩余标题 - 我收到错误消息。

What I want is after the last header, at the end of the document, to exit my Do Loop.我想要的是在文档末尾的最后一个标题之后退出我的 Do Loop。

Here's my code:这是我的代码:

 Sub Changecolortest5()
'
' Changecolortest5 Macro
'
'
    If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
        ActiveWindow.Panes(2).Close
    End If
    If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
        ActivePane.View.Type = wdOutlineView Then
        ActiveWindow.ActivePane.View.Type = wdPrintView
    End If
    Do
    ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
    Selection.MoveDown Unit:=wdParagraph, Count:=1, Extend:=wdExtend
    Selection.Font.Color = 8527984
    ActiveWindow.ActivePane.View.NextHeaderFooter
    Loop
'Exit Header and Footer
    ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
End Sub

Addressing Headers/Footers optimally doesn't work well with recorded macros, so I'm going to show you a slightly different approach than what you give us.以最佳方式解决页眉/页脚不适用于录制的宏,因此我将向您展示一种与您提供的方法略有不同的方法。 The code below works directly with the underlying objects and applies formatting to the Range rather than a selection.下面的代码直接处理底层对象并将格式应用于Range而不是选择。 This is faster and the screen doesn't "flicker".这更快并且屏幕不会“闪烁”。

When working with a group of things, such as Headers, it's more usual to use a For-Each loop to cycle through the group.当处理一组事物时,例如 Headers,更常用的是使用 For-Each 循环在组中循环。 In this case, Headers are specific to Sections, so you loop the Sections.在这种情况下,标题特定于部分,因此您可以循环部分。 Something along these lines:沿着这些路线的东西:

Dim doc as Word.Document
Dim sec as Word.Section

Set doc = ActiveDocument
For Each sec in doc.Sections
  sec.Headers(wdHeaderFooterPrimary).Range.Paragraphs(1).Range.Font.Color = 8527984
  sec.Headers(wdHeaderFooterFirstPage).Range.Paragraphs(1).Range.Font.Color = 8527984
Next

In addition, if you look up the Help topic for Do loops you'll see that they require a test to end the loop: Do While or Do Until or Loop While or Loop Until a certain criterium is met.此外,如果您查看 Do 循环的帮助主题,您会发现它们需要一个测试来结束循环: Do WhileDo UntilLoop WhileLoop Until until 满足某个特定条件。 I'm pretty sure the code you show us must be giving you an error - when asking questions you should always include all relevant information, including any error messages...我很确定您向我们展示的代码肯定会给您一个错误 - 在提出问题时,您应该始终包含所有相关信息,包括任何错误消息......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM