2016-07-16 56 views
0

我想爲Word 2016創建一個VBA宏,刪除下面沒有正文文字的所有標題(即樣式「標題1」和「標題2」)它。澄清一下,這就是我的意思。VBA Microsoft Word 2016宏用於刪除下面沒有文字的標題

  • 運行宏之前:

水果

蘋果和香蕉

蔬菜

糧食

麪包和麪條

  • 運行宏之後:

水果

蘋果和香蕉

籽粒

麪包和意大利麪

我已經能夠使宏刪除所有正文文本或刪除所有標題,但是如何創建一個只刪除下面沒有正文文本的標題的宏?

回答

0

這可以通過在文檔中包含的段落簡單的迭代來完成:

Sub CleanupHeadings() 

    Dim p As Paragraph 
    Dim pNext As Paragraph 

    For Each p In ActiveDocument.Paragraphs 
     If IsHeading(p) Then 
      ' check the following paragraph 
      Set pNext = p.Next 
      If Not pNext Is Nothing Then 
       If IsHeading(pNext) Then 
        ' next paragraph is a heading too, so delete current paragraph 
        p.Range.Delete 
       End If 
      Else 
       ' no following paragraph, i.e. document ends with a heading 
       p.Range.Delete 
      End If 
     End If 
    Next 

End Sub 

Function IsHeading(para As Paragraph) As Boolean 

    IsHeading = para.OutlineLevel < wdOutlineLevelBodyText 

End Function 
相關問題