Word VBA 2010 - 格式化表格单元格中的最后一个段落

时间:2014-03-27 18:26:30

标签: vba word-vba

我有一个项目,我从MadCap Flare导出到Word 2010,我使用VBA脚本来更新文档的格式。我正在尝试检查文档中每个段落的样式,如果它与特定样式匹配,则应用多列表级别格式。

它几乎没有问题。当段落作为表格单元格中的最后一个段落时,会出现问题。在这种情况下,范围包括单元格标记的结尾(因此范围包括单元格的每个段落),因此更改适用于表格单元格中的每个段落而不是简单的最后一个段落。

我使用的代码如下:

For Each iPara In ActiveDocument.Paragraphs
    With iPara.Range
        If iPara.Style.NameLocal = "div_NoteText" Then
            .ListFormat.ApplyListTemplateWithLevel ListTemplate:= _
            ListGalleries(wdOutlineNumberGallery).ListTemplates(1), _
            ContinuePreviousList:=False, ApplyTo:=wdListApplyToWholeList, _
            DefaultListBehavior:=wdWord10ListBehavior, ApplyLevel:=1
        End If
    End With
Next

我需要做些什么更改才能使表格单元格中的最后一个段落工作?

2 个答案:

答案 0 :(得分:3)

“单元格结束”标记是Chr(13)+ Chr(7),因此您可以使用类似下面的代码检测位于单元格末尾的段落:

Sub Tester()
Dim EOC As String
Dim p As Paragraph
Dim rng As Range

    EOC = Chr(13) & Chr(7)

    For Each p In ActiveDocument.Paragraphs

        If Len(p.Range.Text) > Len(EOC) And p.Range.Text Like "*" & EOC Then
               Set rng = p.Range

               'commenting out next line will select the whole cell
               rng.MoveEnd wdCharacter, -1  

               rng.Select
               MsgBox "Found paragraph at end of cell..."
        End If

    Next p

End Sub

答案 1 :(得分:1)

该程序将首先扫描所有不在表格中的段落,然后检查所有表格,仅对每个单元格中最后一个段落应用更改,检查所有段落。

<强> CheckParagraphs

Sub CheckParagraphs()

For Each iPara In ActiveDocument.Paragraphs
    With iPara.Range
        If Selection.Information(wdWithInTable) = False Then
            If iPara.Style.NameLocal = "div_NoteText" Then
                .ListFormat.ApplyListTemplateWithLevel ListTemplate:= _
                ListGalleries(wdOutlineNumberGallery).ListTemplates(1), _
                ContinuePreviousList:=False, ApplyTo:=wdListApplyToWholeList, _
                DefaultListBehavior:=wdWord10ListBehavior, ApplyLevel:=1
            End If
        End If
    End With
Next

CheckTables

End Sub

<强> CheckTables

Sub CheckTables()

Dim oPara As Range
Dim count As Integer
For Each t In ActiveDocument.Tables
    For Each r In t.Rows
        For Each c In r.Cells
            With c.Range
                'Only act on the last paragraph
                With .Paragraphs(.Paragraphs.count).Range
                    If .Style.NameLocal = "div_NoteText" Then
                        .ListFormat.ApplyListTemplateWithLevel ListTemplate:= _
                        ListGalleries(wdOutlineNumberGallery).ListTemplates(1), _
                        ContinuePreviousList:=False, ApplyTo:=wdListApplyToWholeList, _
                        DefaultListBehavior:=wdWord10ListBehavior
                        .SetListLevel Level:=1
                    End If
                End With
            End With
        Next
    Next
Next
End Sub