【问题标题】:replacing text in multiple text files using VBS使用 VBS 替换多个文本文件中的文本
【发布时间】:2020-03-09 05:52:18
【问题描述】:

我正在尝试编写一个 VBS 脚本,该脚本将循环浏览多个文本文件并将多个关键字替换为其他词,例如用 GJA 替换 1ECODE。 我有工作代码可以为单个文件执行此操作,该文件在代码中进行了详细说明,但无法使其循环浏览多个文本文件。

我当前的代码(来自另一个线程)低于它返回错误“对象不支持此属性或方法'f.FullName'

要编辑的文件都称为“testfile_1.txt”、“testfile_2.txt”等

任何人都可以提供任何帮助将不胜感激

Set fso = CreateObject("Scripting.FileSystemObject")

Set prefixes = CreateObject("Scripting.Dictionary")
prefixes.CompareMode = vbTextCompare 'make dictionary lookups case-insensitive
prefixes.Add "testfile", True


For Each f In fso.GetFolder("C:\Users\msi\Documents\script_test\Test_folder").Files
  If InStr(f.Name, "_") > 0 Then
    If prefixes.Exists(Split(f.Name, "_")(0)) Then
      strText = fso.OpenTextFile(f.FullName).ReadAll

      strText = Replace(strText, "1ECODE", "ELH")
      strText = Replace(strText, "1GCODE", "GLH")
      strText = Replace(strText, "2ECODE", "EQT")
      strText = Replace(strText, "2GCODE", "GQT")
      strText = Replace(strText, "3ECODE", "EQT")
      strText = Replace(strText, "3GCODE", "GQT")


 fso.OpenTextFile(f.FullName, 2).Write strText
    End If
     End IF
 Next

【问题讨论】:

  • 你到底在用什么VBAVBSVBA 不同,它将与 Excel、Word 等其他应用程序关联,VBS 可以独立运行。
  • 使用 VBS 独立运行

标签: file text replace vbscript


【解决方案1】:

将代码更改为此,它似乎按要求工作。

Const ForReading = 1
Const ForWriting = 2

Set FSO = CreateObject("Scripting.FileSystemObject")
set objFSO = CreateObject("Scripting.FileSystemObject")
  For Each f In       fso.GetFolder("C:\Users\ms\\Documents\Temporary_delete_every_month\script_test\Test_folder").Files

  msgbox f

set objFile = objFSO.OpenTextFile(f,ForReading)
StrText= objFile.ReadAll
ObjFile.close
Set objFile= nothing

strText = Replace(strText, "1ECODE", "YYY")
strText = Replace(strText, "2ECODE", "XXX")

set objFile = objFSO.OpenTextFile(f,ForWriting)

objFile.WriteLine strText

 objFile.Close

 Next

【讨论】:

    【解决方案2】:

    File 对象没有FullName 属性,请改用Path

    【讨论】:

    • 谢谢你,你能详细说明一下吗?
    • @Matt 您需要使用f.Path,无论您使用过f.FullName
    • 正如@shrivallabha.redij 所说的
    • 抱歉,我的知识不太好,能不能说的更具体一点?
    • 在哪一行?路径正确吗?
    猜你喜欢
    • 1970-01-01
    • 2020-05-27
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    相关资源
    最近更新 更多