I'm currently writing a VBscript to copy data from one text file into another with the goal of skipping the first row. I got a version working with some code I found online, but it does not only skip the first line (this part is working) but it also skips the last line for some reason. I do not want to skip the last line, but I can't figure out what part of the code actually skips my last line. Need: Copy all lines(rows) except first Current code: Copy all lines(rows) except first and last
The text files are both CSV files. Anyone an idea how to achieve what I need, or what part of my code actually lets the last line skip? Thanks in advance.
This is the code:
Sub ChangeCSV(strPath,strCPath)
Dim objFileSys
Dim objInText,objOutText
Dim strData1,strData2
Dim wFlg
wFlg = False
Set objFileSys = CreateObject("Scripting.FileSystemObject")
Set objInText = objFileSys.OpenTextFile(strPath, 1)
Set objOutText = objFileSys.OpenTextFile(strCPath, 2, True)
If objInText.AtEndOfLine = False Then objInText.ReadLine
Do Until objInText.AtEndOfLine = True
strData1 = objInText.ReadLine
If wFlg Then
objOutText.WriteLine strData2
Else
wFlg = True
End If
strData2 = strData1
Loop
objInText.Close
objOutText.Close
Set objInText = Nothing
Set objOutText = Nothing
Set objFileSys = Nothing
End Sub
You want to use the AtEndOfStream property instead of AtEndOfLine
. Here's code that should do what you are expecting:
Dim objFileSys
Dim objInText, objOutText
Dim strLine
Set objFileSys = CreateObject("Scripting.FileSystemObject")
Set objInText = objFileSys.OpenTextFile(strPath, 1)
Set objOutText = objFileSys.OpenTextFile(strCPath, 2, True)
' Read first line
If Not objInText.AtEndOfStream Then objInText.ReadLine
' Read remaining lines
Do While Not objInText.AtEndOfStream
' Get line from source file
strLine = objInText.ReadLine
' Write line to destination file
If objInText.AtEndOfStream Then
objOutText.Write strLine
Else
' Create a new line after writing the line
objOutText.WriteLine strLine
End If
Loop
objInText.Close
objOutText.Close
Set objInText = Nothing
Set objOutText = Nothing
Set objFileSys = Nothing
On the last line, it uses the Write method to avoid creating an extra blank line at the end of the destination file.