條件:1、一個文件夾下有很多「.txt」文件2、每個文件中都有一句或幾句「abc=1234;」,其中「1234」每個地方都確定是幾位數字 要求:將每個文件中的「abc=???;」刪除,保存。 ***********************************************************Option ExplicitPrivate Sub Command1_Click() Dim Arr() As String Dim a As Boolean, i As Long Dim FileNumber, Str Dim Sum As Long "替換次數 Dim Str1 As String "要替換的字元 Dim A1 As Long "需要替換的字元出現的位置 a = SearchFiles("E:新建文件夾 (2)", "*.txt", Arr) "調用函數獲取目錄下所有txt文件 注意目錄後面有斜杠!!! If a Then "如果找到文件 For i = 0 To UBound(Arr) "循環更改讀取到的文件 FileNumber = FreeFile Open Arr(i) For Input As #FileNumber "讀取文件內容 Str = StrConv(InputB(LOF(FileNumber), 1), vbUnicode) Close #FileNumber A1 = InStr(Str, "abc=") "查找 If A1 <> 0 Then "如果找到 Str1 = Mid(Str, A1, 9) "截取A1開始的九個字元 Sum = Sum + 1 "統計替換的次數數 Str = Replace(Str, Str1, "") "替換截取到的字元 FileNumber = FreeFile Open Arr(i) For Output As #FileNumber "替換完成 重新寫入 Print #FileNumber, Str Close #FileNumber End If Next MsgBox " 替換完成 " & vbCrLf _ & "共找到 " & UBound(Arr) - 1 & " 個文件" & vbCrLf _ & "共替換 " & Sum & " 個文件" Else MsgBox " 該目錄下沒有 TXT 文件! " End IfEnd SubFunction SearchFiles(Path As String, FileType As String, ByRef Arr() As String) As Boolean Dim a, b, c As Long Dim sPath As String sPath = Dir(Path & FileType) "查找第一個文件 Do While Len(sPath) "循環到沒有文件為止 ReDim Preserve Arr(0 To a) Arr(a) = Path & sPath "將文件目錄和文件名組合,並存放到數組中 SearchFiles = True a = a + 1 sPath = Dir() "查找下一個文件 DoEvents "讓出控制權 LoopEnd Function
推薦閱讀:

查看原文 >>
相关文章