下面的代码对我来说是将文本文件中的单词(" This")替换为另一个单词("那")。同样我需要用一个单词替换一个单词在同一文本文件中。
我的要求是替换“#34;这个"到"那" 并替换" From" to" TO"。您可以相应地修改以下代码。
Sub ReplaceStringInFile()
Dim objFSO As Object
Dim objFil As Object
Dim objFil2 As Object
Dim StrFileName As String
Dim StrFolder As String
Dim SstrAll As String
Set objFSO = CreateObject("scripting.filesystemobject")
StrFolder = "c:\macro\"
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)
objFil2.Write Replace(strAll, "THIS", "THAT")
objFil2.Close
StrFileName = Dir
Loop
End Sub
答案 0 :(得分:0)
此行代替&#34;此&#34;用&#34;那&#34;。
objFil2.Write Replace(strAll, "THIS", "THAT")
只需在其下添加此行:
objFil2.Write Replace(strAll, "From", "To")
编辑:
抱歉,我还没有测试过代码。试试这个:
Sub ReplaceStringInFile()
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 = "c:\macro\"
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, "THIS", "THAT")
'change from to to in text
newFileText = Replace(newFileText, "from", "to")
'write file with new text
objFil2.Write newFileText
objFil2.Close
StrFileName = Dir
Loop
End Sub
如果有效,请告诉我。
答案 1 :(得分:0)
应该有效。尝试选项比较文本,使其不区分大小写。