【问题标题】:Using Style Headings with Word VBA在 Word VBA 中使用样式标题
【发布时间】:2016-03-29 22:27:21
【问题描述】:

任务是将当前标题分配给比上一个标题低 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

如果有办法做到这一点?

【问题讨论】:

    标签: vba ms-word


    【解决方案1】:

    Selection.Paragraphs.OutlineDemote

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

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

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

    编辑以解决知道哪个标题级别之前的问题,以便决定是降级/提升还是使用同一级别:

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

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

    【讨论】:

    • 谢谢,它运行良好。如果忘记提及的是可以选择插入两个相同级别的标题。因此,如果我第二次使用Selection.Paragraphs.OutlineDemote,它将是另一个较低的标题。我可以使用If 语句,前一个标题在哪里,然后执行OutlineDemoteOutlinePromote。还有其他想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    相关资源
    最近更新 更多