我使用下面的VBA代码替换一个文件夹中所有文件中的几个单词。在相同的VBA代码中,可以复制每个文件的第三行并将其替换为第二行。
Sub ReplaceStringInFile1()
Dim objFSO As Object, objFil As Object, objFil2 As Object
Dim StrFileName As String, StrFolder As String, strAll As String, newFileText As String
Set objFSO = CreateObject("scripting.filesystemobject")
StrFolder = "I:\Documents\ABC\AZ\"
StrFileName = Dir(StrFolder & "*.txt")
Do While StrFileName <> vbNullString
Set objFil = objFSO.opentextfile(StrFolder & StrFileName)
strAll = objFil.readall
objFil.Close
Set objFil2 = objFSO.createtextfile(StrFolder & StrFileName)
'change this to that in text
newFileText = Replace(strAll, "To:", "FROM")
'change from to to in text
newFileText = Replace(newFileText, "THIS", "THAT")
'write file with new text
'change from to to in text
newFileText = Replace(newFileText, "IS", "WAS")
'write file with new text
objFil2.Write newFileText
objFil2.Close
StrFileName = Dir
Loop
End Sub
答案 0 :(得分:1)
我会告诉你逻辑并相应地使用逻辑,并在遇到任何问题时提出代码。
打开每个文本文件ForReading
并使用ReadLine
逐个读取每一行,并使用AtEndOfStream
检查流的结尾。复制一个字符串中的每一行,但跳过第二行。像这样的东西
Do While Obj.AtEndOfStream <> True
Str = Obj.ReadLine
if i = 2 Then
Str = ""
Else
StrF = StrF & Vbcrlf & Str
End If
i = i + 1
Loop
现在打开文本文件ForWriting
使用Obj.Write StrF
替换文件中的旧文本并关闭文件。为文件夹中的所有文件执行循环。
希望这有助于:)