Reputation: 1
I have a folder with text files and data in them, so I want to read all the text files in the folder and write their records into another text file in the same location called outfile
.
From the code I have tried, I'm able to get the records from the text files into the output file (outfile
) but my Do While Not
loop won't terminate. When it reaches the last file it loops again and again from the first file.
I also tried Do While
loop which give me error.
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set folder = objFSO.GetFolder("C:\Precious\Projects\Sources\VBS\Testing")
Set outfile = objFSO.CreateTextFile("C:\Precious\Projects\Sources\VBS\Testing\testout.txt")
for each file in folder.Files
Set testfile = objFSO.OpenTextFile(file.path, ForReading)
Do While Not testfile.AtEndOfStream
line = testfile.readline
outfile.writeline(line)
Loop
testfile.close
next
outfile.close
Upvotes: -1
Views: 446
Reputation: 356
It looks like the list of files includes the newly-created output file. If you must put the output file in the same folder, then get the list of files first:
Dim source
source = "C:\Precious\Projects\Sources\VBS\Testing"
Set folder = objFSO.GetFolder(source)
Dim listOfFiles
Set listOfFiles = folder.Files
Set outfile = objFSO.CreateTextFile(source & "\testout.txt")
For Each file In listOfFiles
The listOfFiles
will be a snapshot of the folder when Set
.
EDIT: ChatGPT misled me when it said the files collection was static. But you can MAKE it static by storing it in an array, if you still want it to be in the same file location:
Dim listOfFiles()
ReDim listOfFiles(0)
For Each file In folder.Files
listOfFiles(UBound(listOfFiles)) = file.path
ReDim Preserve listOfFiles(UBound(listOfFiles) + 1)
Next
ReDim Preserve listOfFiles(UBound(listOfFiles) - 1)
Upvotes: -1