String 如何使用Visual Basic查找和替换多个文件中的文本字符串

String 如何使用Visual Basic查找和替换多个文件中的文本字符串,string,vbscript,replace,String,Vbscript,Replace,我有一个关于简单vbs脚本的基本问题。我的目标是在多个文件中找到替换多个文本字符串的方法。(要替换的21个文本字符串在所有文件中都是相同的。)文件名有大约12个前缀,然后在末尾有数字1到200。我对其中一个文件中的一个字符串使用的基本代码如下所示 Const ForReading = 1 Const ForWriting = 2 Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTe

我有一个关于简单vbs脚本的基本问题。我的目标是在多个文件中找到替换多个文本字符串的方法。(要替换的21个文本字符串在所有文件中都是相同的。)文件名有大约12个前缀,然后在末尾有数字1到200。我对其中一个文件中的一个字符串使用的基本代码如下所示

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
我只想在文件名上循环,也可能在搜索字符串上循环。For…Next循环可以实现这一点吗?我可以引用filename对象中for循环的编号吗


我看到过关于搜索子文件夹的回应,但我认为这比我需要做的要复杂得多

如果文件位于同一目录中,并且所有文件的文件名都类似于
prefix###.txt
,则可以执行以下操作:

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
num = Split(fso.GetBaseName(f.Name), "_")(1)
如果要使用文件名的数字部分,必须从文件名中提取,例如:

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
num = Split(fso.GetBaseName(f.Name), "_")(1)

如果文件不在同一目录中,则需要递归到子文件夹中。另外,如果您的文件名像
prefix_35;##somethingelse.txt
prefix_35;#.otherextension
,则必须添加进一步的检查以将其排除在处理之外。

非常感谢,这非常有用。