Matt
Matt

Reputation: 21

replacing text in multiple text files using VBS

Im trying to write a VBS script that will cycle through multiple text files and replace several keywords with other words e.g. replace 1ECODE with GJA. I have working code that will do this for a single file which is detailed in the code but cant make it cycle through several text files.

my current code (which is from another thread) is below which returns the error "Object doesnt support this property or method 'f.FullName'

The files to edit are all called "testfile_1.txt", "testfile_2.txt" etc etc

any help anyone could offer would be greatly appreciated

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

Upvotes: 1

Views: 139

Answers (2)

Matt
Matt

Reputation: 21

changed the code to this and it appears to be working as required.

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

Upvotes: -1

avb
avb

Reputation: 1753

File object does not have FullName property, use Path instead.

Upvotes: 1

Related Questions