office交流网--QQ交流群号

Access培训群:792054000         Excel免费交流群群:686050929          Outlook交流群:221378704    

Word交流群:218156588             PPT交流群:324131555

VBA代码批量修改或替换文本文件中的内容

2021-02-13 08:00:00
zstmtony
原创
11857

Sub VBA代码批量修改或替换文本文件中的内容()
Dim Fn$, strPath$, strFile$, strText
    Fn = Application.GetOpenFilename("请随便选择一个文件 (*.*), *.*", , "请选择一个文件来获取你的路径")
    strPath = Left(Fn, InStrRev(Fn, ""))
    strFile = Dir(strPath & "*.txt")    ' 读取所有文本文件。
    Do While strFile <> ""    ' 如果文件不为空 就开始循环。
    Open strFile For Input As #1  '打开找到的第一个txt文件
        Open strFile & "_New" For Append As #2   ' 创建这个文件名+_New 的临时文件,并打开它
            Do While Not EOF(1)         '循环至文件结尾
               DoEvents                        '用于大量计算 鼠标卡住
                Line Input #1, strText     '读取这个文件的每一行到变量strText
                If InStr(strText, "Office") > 0 Then  '如果存在“Office”这个关键字
                    Print #2, "微软" & strText       '在前面加微软
                 Else
                    Print #2, strText                    '否则输出原来的内容
                End If
            Loop
         Close #2
     Close #1
     Kill strFile                                       '删除原文件
     Name strFile & "_New" As strFile   '重命名中间临时文件为原文件名
        strFile = Dir             ' 继续查找下一个文件。
    Loop
End Sub
分享