word小工具,替换标题数字开头空格结尾部分为空

Sub ReplaceStartingWith1UntilFirstSpaceInHeading2()
    Dim oPara As Paragraph
    Dim oRange As Range
    Dim regex As Object
    Dim matches As Object
    Dim match As Object

    ' 创建正则表达式对象
    Set regex = CreateObject("VBScript.RegExp")
    With regex
        .Global = True ' 替换所有匹配项
        .IgnoreCase = False ' 区分大小写
        .Pattern = "1[^ ]* " ' 匹配以1开头,直到第一个空格的部分
        .MultiLine = True ' 多行匹配
    End With

    ' 遍历文档中的所有段落
    For Each oPara In ActiveDocument.Paragraphs
        ' 检查是否为第二级标题样式
        If oPara.Style = "标题 2" Then
            Set oRange = oPara.Range
            ' 使用正则表达式在标题中查找匹配的字符串
            Set matches = regex.Execute(oRange.Text)
            If matches.Count > 0 Then
                For Each match In matches
                    ' 替换第一个匹配的字符串
                    oRange.Start = oRange.Start + match.FirstIndex
                    oRange.End = oRange.Start + Len(match.Value)
                    oRange.Text = " " ' 替换为空格
                    oRange.Collapse Direction:=wdCollapseStart ' 折叠范围到开始
                Next match
            End If
        End If
    Next oPara

    MsgBox "完成替换以1开头直到第一个空格的字符串,同时保留格式。"
End Sub

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值