VBA操作WORD(四):获知关键字所在段落及相关信息
思路参考自:http://club.excelhome.net/thread-1477855-1-1.html
以下是代码:
Sub 关键字所在的段落() With Selection .HomeKey unit:=wdStory, Extend:=wdMove If .Find.Execute(FindText:="关键字", Forward:=True) Then '.HomeKey unit:=wdStory, Extend:=wdExtend MsgBox (.Range.Paragraphs.Count) End If End With End Sub
使用例子:
Sub 设置主送对象格式() '规则:如果关键字所在段落只有一句且以冒号结尾,则段落会顶格,不会缩进。默认第一次匹配成功的就是主送对象。 '注意:如果第一段只有一句且,只是“报告如下:”这种格式,程序判断不了,只能个别情况手工调整。 With Selection .HomeKey unit:=wdStory, Extend:=wdMove If .Find.Execute(FindText:=":^p", Forward:=True) Then '.HomeKey unit:=wdStory, Extend:=wdExtend'这句会选定关键字前面所有内容 .MoveStart unit:=wdParagraph, Count:=-1 '选中关键字所在段落 With Selection '注意此处的Selection对象和上一个不同 If (.Range.Paragraphs(.Range.Paragraphs.Count).Range.Sentences.Count = 1) Then .Range.ParagraphFormat.Reset .Range.Style = wdStyleNormal .Range.Collapse Direction:=wdCollapseEnd 'wdCollapseEnd折叠引用整个段落的区域, 则该范围位于结束段落标记之后 (下一段的开头)。 End If End With .MoveStart unit:=wdParagraph, Count:=1 '光标移动到关键字下一个字符 End If End With End Sub