word vba遍历文件,打开另外word修改保存

本文提供了一个使用VBA处理Word文档的脚本,该脚本能够识别并修正文档中的符号错误,将大于等于和小于等于符号的位置进行互换,确保文档内容的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

处理完数个word,回头一看,才发现前面代码把一个符号搞反了。。。

把大于等于与小于等于两符号,颠倒了位置。。。晕。


马上用vba处理一下。


把这些word放在D盘根目录。逐个遍历并打开,逐一修改保存退出。OK!


代码如下:


Sub a()
    Dim doc As Document, myFile As String
    Dim a As Range
    
    myFile = Dir("D:\" & "*.docx")
    
    Do While myFile <> ""
        myFile = "D:\" & myFile
        Set doc = Documents.Open(myFile)
        Set a = doc.Range


        Selection.WholeStory
        '展开域
        Selection.Fields.ToggleShowCodes
        '≥≤ 把大换小,把小换小
        a.Find.Execute FindText:="≤", MatchWildcards:=True, replacewith:="$", Replace:=wdReplaceAll
        a.Find.Execute FindText:="≥", MatchWildcards:=True, replacewith:="#", Replace:=wdReplaceAll
        a.Find.Execute FindText:="$", MatchWildcards:=True, replacewith:="≥", Replace:=wdReplaceAll
        a.Find.Execute FindText:="#", MatchWildcards:=True, replacewith:="≤", Replace:=wdReplaceAll
        Selection.WholeStory
        Selection.Fields.ToggleShowCodes
        
        '保存退出
        doc.Save
        doc.Close
        
        Set doc = Nothing
        
        '查找下一个
        myFile = Dir
    Loop
End Sub


Sub a()
    Dim doc As Document, myFile As String
    Dim a As Range
    
    myFile = Dir("D:\" & "*.docx")
    Do While myFile <> ""
        myFile = "D:\" & myFile
        Set doc = Documents.Open(myFile)
        Set a = doc.Range
        
        Selection.WholeStory
        '展开域
        Selection.Fields.ToggleShowCodes
        '域调整
        a.Find.Execute FindText:="\s( ,", MatchWildcards:=False, replacewith:="\s\do6(", Replace:=wdReplaceAll
        a.Find.Execute FindText:="\s(", MatchWildcards:=False, replacewith:="\s\up7(", Replace:=wdReplaceAll
        Selection.WholeStory
        Selection.Fields.ToggleShowCodes
        
        Dim c As Range, strText As String
        '下标用域
        For Each c In a.Characters
            If c.Font.Subscript = True Then
                c.Select
                strText = Replace(c.Text, Chr(13), "")
                If strText <> "" Then
                    c.Delete
                    Set myfield = Selection.Fields.Add(Range:=Selection.Range, Type:=wdFieldEmpty, PreserveFormatting:=True) '增加一个新域
                    myfield.Code.Text = "eq \s\do4(" & strText & ")"
                Else
                    c.Font.Subscript = False
                End If
            End If
        Next
        
        '保存退出
        doc.Save
        doc.Close
        Set doc = Nothing
        '查找下一个
        myFile = Dir
    Loop
End Sub





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值