【问题标题】:Word Macro - Insert Paragraph with Specific StylesWord 宏 - 插入具有特定样式的段落
【发布时间】:2020-02-19 15:08:09
【问题描述】:

我的 word 文档模板有几种本地样式,它们组合在一起形成一个框(boxPara、boxNote、boxTitle 等)。不幸的是,我所有的盒子都缺少 boxTitle 段落。我的目标是有一个宏来查找第一个 boxPara 并在它之前添加一个空白 boxTitle - 然后查找 boxNote(框中的最后一项)以重置。

问题是我在设置段落样式时遇到了困难。我最接近的是当前段落的样式错误,插入新段落,然后正确地重新设置当前段落的样式。这似乎相当……错误。而且我还希望能够设置插入段落的文本。

Sub addTag()

Dim BoxStart As Integer
Dim Para As Word.Paragraph

BoxStart = 0

For Each Para In ActiveDocument.Paragraphs
    If Para.Format.Style = "BoxParagraph" And BoxStart = 0 Then
        BoxStart = 1
        ' Selection.Paragraphs(1).Range.InsertParagraphBefore

        Para.Format.Style = "BoxTitle"
        Para.Range.InsertParagraph
        Para.Format.Style = "BoxParagraph"

        ' Testing the flag works correctly
        ' Debug.Print BoxStart  
        ' Debug.Print Para.Range.Text
    ElseIf Para.Format.Style = "BoxNote" Then
        BoxStart = 0
        ' Debug.Print BoxStart
    End If

Next

End Sub

【问题讨论】:

    标签: vba ms-word


    【解决方案1】:

    解决办法如下:

    Dim BoxStart As Integer
    Dim Para As Word.Paragraph
    
    BoxStart = 0
    
    For Each Para In ActiveDocument.Paragraphs
        If Para.Format.Style = "BoxParagraph" And BoxStart = 0 Then
            BoxStart = 1
    
            ' Insert Box Title with tags before start of answer boxes
            ' Insert paragraph before current paragraph
            Para.Range.InsertParagraphBefore
    
            ' Select current paragraph
            Para.Range.Select
            ' Move to previous paragraph
            Selection.MoveUp Unit:=wdParagraph, Count:=1
            Selection.MoveEnd Unit:=wdCharacter, Count:=-1
    
            ' format previous pararaph
            Selection.Paragraphs.Format.Style = "BoxTitle"
    
            ' Testing the flag works correctly
            ' Debug.Print BoxStart  
            ' Debug.Print Para.Range.Text
        ElseIf Para.Format.Style = "BoxNote" Then
            BoxStart = 0
            ' Debug.Print BoxStart
        End If
    
    Next
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-24
      相关资源
      最近更新 更多