问题
I have a basic question about a simple vbs script. My goal is to find a replace multiple text strings in multiple files. (The 21 text strings to replace are the same across files.) The file names have about 12 prefixes and then will have numbers 1 to 200 at the end. The basic code I am using for just one of the strings in one of the files is as follows.
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\filename_XX.txt", ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "Test 1", "Test 2")
Set objFile = objFSO.OpenTextFile("C:\filename_XX.txt", ForWriting)
objFile.Write strNewText
objFile.Close
I just want to loop over the file names and possibly loop over the search strings. Could a For...Next loop accomplish this? Can I refer to the number of the for loop in the filename object?
I have seen a response about searching over subfolders, but I think it is more sophisticated than what I need to do.
回答1:
If the files are in the same directory and all have a filename like prefix_##.txt
you could do something like this:
Set fso = CreateObject("Scripting.FileSystemObject")
Set prefixes = CreateObject("Scripting.Dictionary")
prefixes.CompareMode = vbTextCompare 'make dictionary lookups case-insensitive
prefixes.Add "prefix1", True
prefixes.Add "prefix2", True
'...
For Each f In fso.GetFolder("C:\basefolder").Files
If InStr(f.Name, "_") > 0 Then
If prefixes.Exists(Split(f.Name, "_")(0)) Then
text = fso.OpenTextFile(f.FullName).ReadAll
text = Replace(text, "Test 1", "Test 2")
fso.OpenTextFile(f.FullName, 2).Write text
End If
End If
Next
If you want to use the number part of the file name, you have to extract it from the file name, e.g. like this:
num = Split(fso.GetBaseName(f.Name), "_")(1)
If your files are not all in the same directory you'll need to recurse into subfolders. Also, if you have file names like prefix_##somethingelse.txt
or prefix_##.otherextension
, you'll have to add further checks to exclude them from processing.
来源:https://stackoverflow.com/questions/15424568/how-to-find-and-replace-text-strings-in-multiple-files-using-visual-basic