2

我需要帮助创建查找和替换字符串宏,以便它可以在文件夹中的所有文件中查找和替换字符串。

例如 fofler ="C:\ifolder\" 文件列表 ="*.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
4

1 回答 1

3

因为您实际上有打开文本文件的代码 - 而不是 Excel 文件 - 我遵循了相同的方法

像这样的东西在哪里

  1. Dir用于循环遍历特定文件夹中的所有
  2. 使用 FileScriptingObject 一次读取所有文本,进行替换,然后用更新的文本覆盖文件文件。

代码

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
于 2013-02-13T09:54:46.080 回答