[英]How to detect if the previous heading in the document is heading 1 or heading 7 through VBA
My templates contain Heading 1 to 5 for normal text and Appendix headings (based on heading 7, 8 and 9).我的模板包含普通文本的标题 1 到 5 和附录标题(基于标题 7、8 和 9)。
Appendix A Chapter text附录 A 章节正文
The table and figure captions are different: based on Heading 1 or Appendix.表格和图标题不同:基于标题 1 或附录。
Works fine.工作正常。 But ... for now I have two buttons in the ribbon to insert the table caption:但是......现在我在功能区中有两个按钮来插入表格标题:
Same for figure caption.图形标题相同。
There must be a way to detect the previous main heading (heading 1 or heading 7 or outlinelevel 1 or 7), so I only need one button to insert a table (or figure) caption.必须有一种方法可以检测到以前的主标题(标题 1 或标题 7 或大纲级别 1 或 7),因此我只需要一个按钮即可插入表格(或图形)标题。 But I just can't find it.但我就是找不到。
Does anyone have a clue?有人有线索吗? Thank you.谢谢你。 Helma海尔玛
There is no specific property in Word that will return the previous level with outline level x. Word 中没有特定属性会返回大纲级别为 x 的前一个级别。 You will need to create a macro that loops backwards from the current paragraph until it finds outline level 1 or outline level 7.您将需要创建一个从当前段落向后循环的宏,直到找到大纲级别 1 或大纲级别 7。
Here are two examples of a function that return true if a preceding heading level was outline level 7 and false if it was outline level 1. The code compile without error and have no findings when inspected with the RubberDuck code inspector.下面是两个函数示例,如果前面的标题级别为大纲级别 7,则返回 true,如果大纲级别为 1,则返回 false。代码编译没有错误,并且在使用 RubberDuck 代码检查器检查时没有发现任何问题。
Option Explicit
'Recursive function
Public Function IsAppendixR(ByVal ipPara As Range) As Boolean
Select Case ipPara.Paragraphs.Item(1).OutlineLevel
Case 1
IsAppendixR = False
Case 7
IsAppendixR = True
Case Else
IsAppendixR = IsAppendixR(ipPara.Previous)
End Select
End Function
' Loop version
Public Function IsAppendixL(ByVal ipPara As Range) As Boolean
Do
Select Case ipPara.Paragraphs.Item(1).OutlineLevel
Case 1
IsAppendixL = False
Exit Function
Case 7
IsAppendixL = True
Exit Function
Case Else
ipPara.Previous
End Select
Loop
End Function
Word contains a hidden bookmark that you can use to get the range of the current heading level. Word 包含一个隐藏的书签,可用于获取当前标题级别的范围。 By testing the outline level of the first paragraph in that range you can determine whether you are in an appendix.通过测试该范围内第一段的大纲级别,您可以确定您是否在附录中。
Sub TestIsAppendix()
If IsAppendix(Selection.Range) Then MsgBox "In appendix"
End Sub
Public Function IsAppendix(ByVal para As Range) As Boolean
Dim headingBlock As Range
Set headingBlock = para.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")
Select Case headingBlock.Paragraphs.Item(1).OutlineLevel
Case 7 To 9
IsAppendix = True
Case Else
IsAppendix = False
End Select
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.