Function select_range(start_title_str As String, end_title_str As String, Optional style_str As String = "标题 1") As Boolean
'选择范围,通过指定本标题字符串(start_title_str)和下一个标题字符串(end_title_str),选择它们之间的内容
'若是end_title_str为空,则认为从start_title_str开始选择到当前节的末尾
'style_str是可选参数,它有一个默认值,该值用于查询的时候指定标题样式名
'若是start_title_str为空,则不进行任何操作
'本函数成功选择则返回true,失败返回false
If (Len(start_title_str) <> 0) Then
Selection.Find.ClearFormatting
Selection.Find.Style = ActiveDocument.Styles(style_str)
With Selection.Find
.Text = start_title_str
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False '是否区分大小写
.MatchWholeWord = False
.MatchByte = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.MatchWholeWord = True '是否全字匹配
.Execute
End With
If (Selection.Find.Found) Then
range_start_index = Selection.Start + Len((Selection.Paragraphs(1).Range.Text)) '当前选择的内容的起始字符index
If (Len(end_title_str) <> 0) Then
Selection.Find.Text = end_title_str
Selection.Find.ClearFormatting
Selection.Find.Style = ActiveDocument.Styles(style_str)
With Selection.Find
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False '是否区分大小写
.MatchWholeWord = False
.MatchByte = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.MatchWholeWord = True '是否全字匹配
.Execute
End With
If (Selection.Find.Found) Then
range_end_index = Selection.Start
Selection.Start = range_start_index '设定选择的开始位置
Selection.End = range_end_index '设定选择的结束位置
select_range = True
Else
MsgBox ("未查询到 " + end_title_str)
select_range = False
End If
Else
Selection.Start = range_start_index '设定选择的开始位置
Selection.Expand (wdSection) '拓展选择到当前所在节的末尾
select_range = True
End If
Else
MsgBox ("未查询到 " + start_title_str)
select_range = False
End If
Else
select_range = False
End If
End Function