Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

VBS script to open any file in a folder.

Status
Not open for further replies.

xcaliber13

Technical User
Dec 23, 2014
2
US
I need a little help with this vbs script. The script works great but I want to be able to open any file that is in the folder without having to give the exact name of the file.

Here is the script:

Const ForReading = 1
Const ForWriting = 2


Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\temp\test.txt", ForReading)

strText = objFil.ReadAll
objFile.Close
strNewText = Replace(strText, "CH00", "")


Set objFil = objFSO.OpenTextFile("C:\temp\test.txt", ForWriting)
objFile.WriteLine strNewText
objFile.Close

I cannot figure out how to get this script to open any (*.txt) file in the C:\temp folder
Any help would be Great
 
Something like this:
Code:
Set objFolder = objFSO.GetFolder("C:\temp")
For Each objFile in objFolder.Files
   If LCase(Right(objFile.Path, 4)) = ".txt" Then
      'do something
   End If
Next
 
guitarzan,
Thank you for the quick reply. But I am not understanding how:

Set objFolder = objFSO.GetFolder("C:\temp")
For Each objFile in objFolder.Files
If LCase(Right(objFile.Path, 4)) = ".txt" Then
'do something
End If
Next

Replaces:

Set objFile = objFSO.OpenTextFile("C:\temp\test.txt", ForReading)

and

Set objFil = objFSO.OpenTextFile("C:\temp\test.txt", ForWriting)



 
Its a loop. Each pass through the loop, objFile.Path will be the full path to the next text file. So

[pre]Set objFile = objFSO.OpenTextFile("C:\temp\test.txt", ForReading)[/pre]

Becomes

[pre]Set objFile = objFSO.OpenTextFile(objFile.Path, ForReading)[/pre]

etc

the line "do something" was meant to indicate where you would put your code, whatever it is you want to do
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top