Word VBA: 根据光标位置一键选择上下文

对于大篇幅的Word文档,有时会碰到好几页的段落、章节或表格,如果用鼠标拖动来选择文本就不太方便。以下代码实现了自动选择上下文,根据光标所在位置的大纲级别,自动选择正文、一个章节、同级别章节、整个表格等。

Sub SelectContext()
'
' 根据光标位置,选择上下文
'

    Dim cur As Range
    Dim rng As Range
    Dim lv&, a&, b&
    
    Set rng = Selection.Range
    
    If rng.Information(wdWithInTable) Then  ' 光标在表格内,则选中整个表格
        rng.Tables(1).Select
        Exit Sub
    End If
    
    lv = rng.ParagraphFormat.OutlineLevel
    Set cur = rng.Paragraphs(1).Range
    
    If lv = wdOutlineLevel1 Then  ' 光标在一级标题,则选中当前章节全部内容
    
        Set rng = cur
        a = rng.Start
        Do
            b = rng.End
            Set rng = rng.Next(wdParagraph)
            If rng Is Nothing Then Exit Do
        Loop While rng.ParagraphFormat.OutlineLevel > wdOutlineLevel1
    
    ElseIf lv = wdOutlineLevelBodyText Then  ' 光标在正文,则选中当前章节正文全部内容
        
        Set rng = cur
        Do
            a = rng.Start
            Set rng = rng.Previous(wdParagraph)
            If rng Is Nothing Then Exit Do
        Loop While rng.ParagraphFormat.OutlineLevel = wdOutlineLevelBodyText
        
        Set rng = cur
        Do
            b = rng.End
            Set rng = rng.Next(wdParagraph)
            If rng Is Nothing Then Exit Do
        Loop While rng.ParagraphFormat.OutlineLevel = wdOutlineLevelBodyText
    
    Else  ' 光标在2~9级标题,则选中平级章节内容
        
        Set rng = cur
        Do
            If rng.ParagraphFormat.OutlineLevel = lv Then a = rng.Start
            Set rng = rng.Previous(wdParagraph)
            If rng Is Nothing Then Exit Do
        Loop While rng.ParagraphFormat.OutlineLevel >= lv
        
        Set rng = cur
        Do
            b = rng.End
            Set rng = rng.Next(wdParagraph)
            If rng Is Nothing Then Exit Do
        Loop While rng.ParagraphFormat.OutlineLevel >= lv
    End If
    
    Set rng = ActiveDocument.Range(a, b)
    rng.Select
    
End Sub
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值