使用Word VBA样式标题

时间:2015-10-27 12:54:53

标签: vba ms-word word-vba

任务是将当前标题分配给标题,该标题比上一标题低1级。

问题是前一个标题会逐段更改,具体取决于文档。

目前我有以下内容:

'Setting a Temp Bookmark to come back to
ActiveDocument.Bookmarks.Add Name:="CurrentPosition", Range:=Selection.Range

'Going Back to the previous Heading
Selection.GoTo What:=wdGoToBookmark, Name:="PreviousHeading"

'Determining the current and assigning the next style
If Selection.Style = ActiveDocument.Styles("Heading 1") Then
    NextHeadingStyle= ActiveDocument.Styles("Heading 2")
ElseIf Selection.Style = ActiveDocument.Styles("Heading 2") Then
    NextHeadingStyle= ActiveDocument.Styles("Heading 3")
ElseIf Selection.Style = ActiveDocument.Styles("Heading 3") Then
    NextHeadingStyle= ActiveDocument.Styles("Heading 4")
ElseIf Selection.Style = ActiveDocument.Styles("Heading 4") Then
    NextHeadingStyle= ActiveDocument.Styles("Heading 5")
ElseIf Selection.Style = ActiveDocument.Styles("Heading 5") Then 
    NextHeadingStyle= ActiveDocument.Styles("Heading 6")
End If

'Going back to the new Heading
Selection.GoTo What:=wdGoToBookmark, Name:="CurrentPosition"

'Changing the Style accordingly
Selection.Style = NextHeadingStyle  

作为测试,我尝试的是:

 Selection.Style = wdStyleHeading4 - 1

然后将文本设置为"标题5"

我想要的是:

'Setting a Temp Bookmark to come back to
ActiveDocument.Bookmarks.Add Name:="CurrentPosition", Range:=Selection.Range

'Going Back to the previous Heading
Selection.GoTo What:=wdGoToBookmark, Name:="PreviousHeading"

NextHeadingStyle = Selection.Style
NextHeadingStyle = NextHeadingStyle - 1

'Going back to the new Heading
Selection.GoTo What:=wdGoToBookmark, Name:="CurrentPosition"

'Changing the Style accordingly
Selection.Style = NextHeadingStyle

如果有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

Selection.Paragraphs.OutlineDemote

这相当于在Word UI中按Alt + Shift +向右箭头。

请注意,还有相反的结果:OutlinePromote。还有OutlineDemoteToBody,它删除了标题格式并应用了Normal样式。

这些都起源于大纲视图,但也适用于打印版面。

编辑以解决知道哪个标题级别先于以决定是否降级/提升或使用相同级别:

以下内容返回当前选择正上方的标题级别样式。

Document.Bookmarks("\HeadingLevel").Range.Paragraphs(1).Range.Style