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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM