office交流網--QQ交流群號

Access培訓群:792054000         Excel免費交流群群:686050929          Outlook交流群:221378704    

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

VBA代碼批量修改或替換文本文件中的內容

2021-02-13 08:00:00
zstmtony
原創
11852

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
分享