office交流網(wǎng)--QQ交流群號及微信交流群

Access培訓(xùn)群:792054000         Excel免費交流群群:686050929          Outlook交流群:221378704    

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

微信交流群(請用微信掃碼)

        

VBA代碼批量修改或替換文本文件中的內(nèi)容

2021-02-13 08:00:00
zstmtony
原創(chuàng)
13039

Sub VBA代碼批量修改或替換文本文件中的內(nèi)容()
Dim Fn$, strPath$, strFile$, strText
    Fn = Application.GetOpenFilename("請隨便選擇一個文件 (*.*), *.*", , "請選擇一個文件來獲取你的路徑")
    strPath = Left(Fn, InStrRev(Fn, ""))
    strFile = Dir(strPath & "*.txt")    ' 讀取所有文本文件。
    Do While strFile <> ""    ' 如果文件不為空 就開始循環(huán)。
    Open strFile For Input As #1  '打開找到的第一個txt文件
        Open strFile & "_New" For Append As #2   ' 創(chuàng)建這個文件名+_New 的臨時文件,并打開它
            Do While Not EOF(1)         '循環(huán)至文件結(jié)尾
               DoEvents                        '用于大量計算 鼠標(biāo)卡住
                Line Input #1, strText     '讀取這個文件的每一行到變量strText
                If InStr(strText, "Office") > 0 Then  '如果存在“Office”這個關(guān)鍵字
                    Print #2, "微軟" & strText       '在前面加微軟
                 Else
                    Print #2, strText                    '否則輸出原來的內(nèi)容
                End If
            Loop
         Close #2
     Close #1
     Kill strFile                                       '刪除原文件
     Name strFile & "_New" As strFile   '重命名中間臨時文件為原文件名
        strFile = Dir             ' 繼續(xù)查找下一個文件。
    Loop
End Sub
分享
文章分類
聯(lián)系我們
聯(lián)系人: 王先生
Email: 18449932@qq.com
QQ: 18449932
微博: officecn01
移動訪問