EOF VBA blocks me from accessing last line of my file - vba

I am trying to loop through a text file. I do specific check on each line of this file to know if it will be pasted or not. I am using the following code. But using EOF blocks me from accessing the last line, which can be useful sometimes.
Dim buffer As String
Open file For Input As #1
Line Input #1, buffer
i = 1
j = 1
Do Until EOF(1) And i > coll(coll.Count)
If i = coll(j) Then
ListSplit = Split(buffer, ",") 'Split the line with "," delimiter
'...
j=j+1
End If
Line Input #1, buffer
i = i + 1
Loop
Close #1

Structure your logic like this:
Open file For Input As #1
Do
Line Input #1, buffer
Debug.Print buffer 'do your work
Loop Until EOF(1)
Close #1
The issue with the code you posted is that the last line is read, which sets EOF, and then you loop. The condition is evaluated and the loop is exited.

Related

Is there a way to read a file one line at a time using a different delimiter than VBA's default (vbCr/vbCrLf)?

I am trying to read a multi-line .csv file and put each token inside its own cell within Excel. The issue is that I have no control over the incoming .csv files.
They are all the same in terms of number of columns (variable number of rows, though, but that's easy to account for). However, for whatever reason the source of the .csv files sometimes puts a CRLF at the end of the header line and sometimes it puts only an LF. Again, I have no control over this so I must code around the variability.
As far as I understand, the VBA line Line Input #1, strLine uses either CR or CRLF to delimit lines, which makes sense. I have attempted to place the entire .csv file's contents into a single string and then use Replace strFileContents, vbCr, "" to eliminate all CR characters, but it seems as though this got rid of all later occurrences of CRLF as well and leaves me where I started.
So, is there a way for me to accept one line at a time using Line Input #1, strLine but a LF delimiter? Or is there another way I can manipulate the entire contents of a string (i.e. getting rid of only CR and not the instances of CRLF) and Split() the string from there?
Here is a shortened version of my code:
Dim Column, Row As Integer 'used Sheets().Input(Row, Column).Value to insert strings
Open strFilePath For Input Access Read As #1
Do Until EOF(1)
Line Input #1, strLine
strLine = Split(strLine, vbLf)(1)
arr = Split(strLine, ",")
For Column = 1 to 8
'insert stuff
Next Column
Row = Row + 1
Loop
However this doesn't quite work for me, and I believe if it did I would still have to deal with the extra CR chars.
Thank you.
asc(vbLF)=10
asc(vbCR)=13
asc(vbCRLF)=13
So Replace vbLF only.
Example
Sub test()
Dim strTest As String
strTest = "First Line " & vbLf & "Second Line" & vbCrLf & "Third Line" & vbCr & "Fourth Line"
strTest = Replace(strTest, vbCrLf, vbCr) '/ Gets rid of double line breaks caused by next replacement
strTest = Replace(strTest, vbLf, vbCr)
MsgBox strTest
End Sub

Looping CSV files in VBA with paragraph marker

I have a CSV file with paragraph marker at the end of every line, I have to loop the CSV file and copied to the excel sheet using VBA. Please find the below code which I am using,
Dim filePath As String
Dim row_number As Integer
Dim col_number As Integer
Dim lineFromFile As String
Dim lineItems As Variant
fileName = "D:\test.csv"
Open filePath For Input As #1
row_number = 1
Do Until EOF(1)
Line Input #1, lineFromFile
lineItems = Split(lineFromFile, ",")
col_number = 1
For i = 0 To 15
Sheets("Sheet1").Rows(row_number).Columns(col_number + i).value = lineItems(i)
row_number = row_number + 1
Loop
Close #1
Image for CSV file showing paragraph marker
What is the problem is EOF will be getting true when the controller reached paragraph marker at the end and it is reading only the first line. Please give some input on this.
I'm not exceptionally well versed in reading text files, but unless there's a way to change what VBA is seeing as the EOL marker, you'll have to read the file one character at a time, filling your own internal string buffer until you reach the paragraph marker.
i.e. ReplaceLine Input #1, lineFromFilewith your own function - something like this:lineFromFile = ReadALineFromMyFile(#1)that reads one character at a time and returns lineFromFile once it's found the paragraph marker.
Your code will then recognize that as "EOL" and can process the line buffer you've been filling.
Lather, rinse, repeat until you reach the true EOF.
I got a solution for this. I can't read the files by looping because of the line feed at the end. So I will split the lines and reading data by follows,
Line Input #1, lineFromFile
lines = Split(lineFromFile, vbLf)
For Each line In lines
lineItems = Split(line, ",")
Sheets("Sheet1").Rows(row_number).Columns(col_number + i).value = lineItems(i)
Next line
This is working fine for me. Thanks #FreeMan,Luuklag.

New line character issue when appending new line to a text file using vba macro

So, I have this piece of code which do exactly what I want: append a new line into a text file using the contents of the cell A1. But when I look at the file, The lines have that "new line" character. How can I avoid my code to write that character?
That's my code.
Sub append_data()
Dim srtfile_path As String
strfile_path = "C:\Users\me\textfile.txt"
output = StrConv(Worksheets("Sheet1").Range("A1"), vbUnicode)
linebreak = StrConv(vbNewLine, vbUnicode)
Open strfile_path For Append As #1
Print #1, output + linebreak
Close #1
End Sub
If you wish to not only delete the linebreak that you are explicitly writing, but also the linebreak that separates one line from the next in a text file, you need to place a semi-colon (;) at the end of the Print statement:
Sub append_data()
Dim srtfile_path As String
strfile_path = "C:\Users\me\textfile.txt"
output = StrConv(Worksheets("Sheet1").Range("A1"), vbUnicode)
Open strfile_path For Append As #1
Print #1, output;
Close #1
End Sub

VBA - Identify and Copy Row from .txt file

I'm using the following code to go line by line through a txt file and (1) identify a text string and (2) import the following 50 digits. I'd like to find a way to import the entire ROW from the txt file but am unsure the code. Also, is there a way to tell VBA to find the SECOND or THIRD string in the txt file? Currently the code below is simply locating the first occurrence. Thank you!!
Sub CopyTXT()
myFile = "G:\Filings\Test\Test.txt"
Open myFile For Input As #1
Do Until EOF(1)
Line Input #1, textline
Text = Text & textline
Loop
Close #1
Revenue = InStr(Text, "Operating Revenues")
'This is where I'm confused - not sure how to copy that row, so I simply pick a large value and use a mid formula - would like to change this.
Range("H1").Value = Mid(Text, Revenue + 7, 50)
End Sub
Something like this (assuming the text you're looking for is on a single line and not split across lines)
Sub CopyTXT()
Dim myFile, textline
Dim i As Long
i = 0
myFile = "G:\Filings\Test\Test.txt"
Open myFile For Input As #1
Do Until EOF(1)
Line Input #1, textline
If InStr(textline, "Operating Revenues") > 0 Then
i = i + 1
If i = 2 Then
Range("H1").Value = textline
End If
End If
Loop
Close #1
End Sub

Move cursor to write in specific line of a text file with VBA

I would like to know how I can use VBA to replace a specific line of a text file by another text, and to write in specific zone of the text file by moving the cursor.
How about this:
Dim TextString As Variant
'read text from file
TextString = Split(CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\sometext.txt").ReadAll, Chr(13) & Chr(10))
'change your text here as TextString(#Line - 1) = "Text"
'still assume you want to replace line 5
TextString(4) = "New Text"
'write back in file
CreateObject("Scripting.FileSystemObject").CreateTextFile("C:\sometext.txt").Write (Join(TextString, Chr(13) & Chr(10)))
I think it's pretty simple cuz there is only one line to read and another one to write. No loops or closing files or anything like that.
You would need to keep track of the positions yourself and apply the logic accordingly.
Something like this:
Dim text As String, allText As String
Dim lineNumber As Integer
' Open read handle.
Open "C:\sometext.txt" For Input As #1
allText = ""
lineNumber = 0
Do Until EOF(1)
lineNumber = lineNumber + 1
Line Input #1, text
' Assume you want to replace line 5.
If lineNumber = 5 Then
text = "My new value"
End if
allText = allText & vbCrLf & text
Loop
' Close read handle.
Close #1
' Output the new text to a separate file.
Open "C:\updatedtext.txt" For Append As #1
Write #1, allText
Close #1