我需要帮助创建查找和替换字符串宏,以便它可以在文件夹中的所有文件中查找和替换字符串。
例如fofler = "C:\ifolder\"
files list = "*.xlsx"
到目前为止,我只能为一个文件执行此操作,我需要对文件夹中的所有文件执行此操作
Sub ReplaceStringInFile()
Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String
' Edit as needed
sFileName = "C:\macro\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
答案 0 :(得分:3)
因为你实际上有打开文本文件的代码 - 而不是Excel文件 - 我采用了相同的方法
像这样的地方
Dir
用于遍历特定文件夹中的所有txt个文件。<强>码强>
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