Excel宏可在任何文本文件中查找和替换多个字符串 [英] Excel macro to find and replace multiple strings in any text file
本文介绍了Excel宏可在任何文本文件中查找和替换多个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我天真地喜欢脚本,但是我使用了您网站上的以下代码来替换文本文件中的字符串,并且效果很好.但是,我不想指定文件名,它应该准备好任何文件(例如* .txt或* .xml).因此,如果有人可以提供帮助,我表示感谢.
I am naive to scripts, but I used below code from your site to replace strings in a text file and it works fine. But, I don't want specify a file name, it should ready any file like (*.txt or *.xml). So, I appreciate if anyone could help in this.
谢谢
Sub ReplaceStringInFile()
Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String
' Edit as needed
sFileName = "C:\Temp\test.txt"
iFileNum = FreeFile
Open sFileName For Input As iFileNum
Do Until EOF(iFileNum)
Line Input #iFileNum, sBuf
sTemp = sTemp & sBuf & vbCrLf
Loop
Close iFileNum
sTemp = Replace(sTemp, "THIS", "THAT")
iFileNum = FreeFile
Open sFileName For Output As iFileNum
Print #iFileNum, sTemp
Close iFileNum
End Sub
推荐答案
Sub ReplaceStringInFile()
Dim sBuf As String
Dim sTemp As String
Dim sFileName As String
Dim FileExt(2) As String
ruta = Application.ActiveWorkbook.Path
ChDrive ruta
ChDir ruta
FileExt(1) = "txt"
FileExt(2) = "xml"
For i = 1 To 2
sFileName = Dir("*." & FileExt(i))
Do
If sFileName = "" Then Exit Do
sTemp = ""
Open sFileName For Input As #1
Do Until EOF(1)
Line Input #1, sBuf
sTemp = sTemp & sBuf & vbCrLf
Loop
Close #1
sTemp = Replace(sTemp, "THIS", "THAT")
Open sFileName For Output As #1
Print #1, sTemp
Close #1
sFileName = Dir()
Loop
Next i
End Sub
这篇关于Excel宏可在任何文本文件中查找和替换多个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文