line input not working as expected in VBA - vba

I have a text file that I open and attempt to read the individual lines. I have used the same code before on other files with no problem, but for some reason, this particular file is strange. When I do the following command;
Line Input #1, read_string
the string read_string contains the entire sequence of each line in the file concatenated together. When I look at the special chararcters of the file I do see a cariage return. But just so you know what the file looks like, here are the first two lines (daniweb formatting is too strange to print text here),
k_arr[8'h1C]= {10'b001111_0100,10'b110000_1011} ;
k_arr[8'h1C]= {10'b001111_0100,10'b110000_1011} ;
Anybody know how I can read each line? apparently line input doesnt work for this file.

Try
Dim lines() As String
lines = Split(read_string, vbCr) 'splitting with Carriage Return delimiter
'did it work?
Debug.Print lines(1)
Debug.Print lines(2) Dim lines() As String
Each element of the lines array should now contain one line of your text file.
If it didn't work, try with another delimiter instead of vbCr, e.g. vbLf (line feed).

Related

How to read a single line out of a word document

The method I used was for text files and gives gibberish as expected.
In: John Smith
Out: PK!~8ìz‡­[Content_Types].xml ¢( ´”ÏNÂ#Æï&¾C³WÓ.x0ÆP8•D|€a;…Õvw³;ü{{§´5#UôBRf¾ß÷Ív;½Áº,¢%ú ­IE7鈲™6³T¼Lâ[“Aa
¦bƒAú—½ÉÆaˆXmB*æDîNÊ æXBH¬CÕÜúˆýL:Po0CyÝéÜHe
¡¡˜*†è÷†˜Ã¢ h´æ¿ë$SmDt_÷UV©ç
­€¸,—&KÊÛ<×
I'm a novice at VBA, and I'm trying to read a document line by line so that I can eventually have the macro automatically remove entire lines based on their content.
Sub ayaya()
Dim TextLine As String
Open ActiveDocument.Path & "\Doc1.docm" For Input As #1
Do While Not EOF(1) ' Loop until end of file.
Line Input #1, TextLine ' Read line into variable.
Debug.Print TextLine
Loop
Close #1
End Sub
Part of me hoped that it would give "John Smith". I've seen some solutions put the entire document into a text file. Is there any way where I can delimit the data somehow? I'd like to be able to isolate a single line and remove it.
You are trying to read a docx or docm file, which is a zip archive. Word files are not plain text files, so you won't get anything meaningful treating them as such. You need to open the file with Word or another app that can read such files.

Having issues with illegal characters in file path

I am writing a program in VB.NET which loops through a file with some file paths in it to perform an action on. The file paths in this file are each on a line, and i'm looping through the file like:
Dim FileContents As String
FileContents = System.IO.File.ReadAllText("C:\File.txt")
Dim FileSplit As String()
FileSplit = FileContents.Split(vbCrLf)
For Each ThisLine In FileSplit
Dim FileModified As Date
FileModified = System.IO.File.GetLastWriteTime(ThisLine)
'Do something here
Next
Contents of File.txt is:
Y:\Users\localadmin\Desktop\MakeShadowCopy\FileInfo.vb
Y:\Users\localadmin\Desktop\MakeShadowCopy\FindFiles.vb
Y:\Users\localadmin\Desktop\MakeShadowCopy\MakeShadowCopy.sln
Y:\Users\localadmin\Desktop\MakeShadowCopy\MakeShadowCopy.v12.suo
The loop works fine, but it is throwing an exception on the line with GetLastWriteTime() on it, saying that the path contains illegal characters, but it is just a normal string with a file path in it.
If anyone has any ideas, or know how to escape the string going into GetLastWriteTime() that would be much appreciated :)
Thanks!
Probably the lines in your file are not correctly vbCrLf terminated.
If this is the case the Split cannot divide correctly your input in lines and you end up with the whole text passed to the GetLastWriteTime.
Instead of using ReadAllText you could use ReadAllLines and let the work to split the lines to the Framework that knows how to handle the file line break and carriage return codes.
For Each ThisLine In System.IO.File.ReadAllLines("C:\file.txt")
Dim FileModified As Date
FileModified = System.IO.File.GetLastWriteTime(ThisLine.Trim())
Next
Also add a Trim to the ThisLine variable to remove some unseen character added erroneusly to the line
Two ideas:
Use For instead of For Each and ensure that you're getting exception on the very first iteration. If not, you may have issues with one specific file path. Check out iteration variable value if that is the case.
Open the file in a hex editor and ensure that each line is terminating properly. You might have either CR (10) or LF(13) character at the end but not both as normal in Windows.

Writing from multiline text box to .txt file, and then reading it back

I have a form with several text boxes and I want to write the contents of each of them to a new line in a .txt file. As in, the user fills in a form, and the info is stored in the file. Then I want to be able to retrieve the info from the file into the same text boxes. I am able to do this, so far, but I encounter problems when one of the text boxes is multiline.
Printline(1, txtBox1.text)
Printline(1, txtBox2.text)´which is the multiline one
Printline(1, txtBox3.text)
When I read this back from the file I get the second line of the multiline text box where I want the text from txtBox3 to be.
LineInput(1, txtBox1.text)
LineInput(1, txtBox2.text)
LineInput(1, txtBox3.text)
How can I get all the lines from the multiline text box to write to one line in the file, and then read it back as separate lines in a multiline text box?
I hope I am making sense? I really would like to keep the logic of "one txtBox - one line in the file"
I guess I need to use different methods of writing and reading, but I am not that familiar with this, so any help is much appreciated.
You can rely on the Lines Property in case of having more than one line. Sample code (curTextBox is the given TextBox Control):
Using writer As System.IO.StreamWriter = New System.IO.StreamWriter("path", True)
Dim curLine As String = curTextBox.Text
If (curTextBox.Lines.Count > 1) Then
curLine = ""
For Each line As String In curTextBox.Lines
curLine = curLine & " " & line
Next
curLine = curLine.Trim()
End If
writer.WriteLine(curLine)
End Using
NOTE: this code puts in one line all the text from the given TextBox independently upon its number of lines. If it has more than one line, it includes a blank space to separate the individual lines (all of them fitting in a single line of the file anyway). You might want to change this last feature by adding a different separating character (replace & " " & with the one you want).
One option would be to escape the newlines so that they aren't in the output, then unescape them on reading back in.
Here's some example code that will do this (I've never written VB before, so this probably isn't idiomatic):
' To output to a file:
Dim output As String = TextBox2.Text
' Escape all the backslashes and then the vbCrLfs
output = output.Replace("\", "\bk").Replace(vbCrLf, "\crlf")
' Write the data from output to the file
' To read data from the file:
Dim input As String = ' Put the data from the file in input
' Put vbCrLfs back for \crlf, then put \ for \bk
input = input.Replace("\crlf", vbCrLf).Replace("\bk", "\")
' Put the text back in its box
TextBox2.Text = input
Another option would be to store your data in XML, JSON, or YAML. Any of those are text-based formats that will require a library to parse, but should cleanly handle the multiline text you have, along with providing increased future flexibility.
the next simple code works for me.
Saving multiline text to a single line in a file:
str = Replace(MyTextBox.Text, Chr(13) & Chr(10), "*LineFeed*") 'something recognizable
Print #1, str 'no quotes
To get the string from the file and put it on a TextBox:
Line Input #1, str
MyTextBox.Text = Replace(str, "*LineFeed*", Chr(13) & Chr(10))
Hope this helps

How to : streamreader in csv file splits to next if lowercase followed by uppercase in line

I am using asp.Net MVC application to upload the excel data from its CSV form to database. While reading the csv file using the Stream Reader, if line contains lower case letter followed by Upper case, it splits in two line . EX.
Line :"1,This is nothing but the Example to explanationIt results wrong, testing example"
This line splits to :
Line 1: 1,This is nothing but the Example to explanation"
Line 2:""
Line 3:It results wrong, testing example
where as CSV file generates right as ""1,This is nothing but the Example to explanationIt results wrong, testing example"
code :
Dim csvFileReader As New StreamReader("my csv file Path")
While Not csvFileReader.EndOfStream()
Dim _line = csvFileReader.ReadLine()
End While
Why should this is happening ? how to resolve this.
When a cell in an excel spreadsheet contains multiple lines, and it is saved to a CSV file, excel separates the lines in the cell with a line-feed character (ASCII value 0x0A). Each row in the spreadsheet is separated with the typical carriage-return/line-feed pair (0x0D 0x0A). When you open the CSV file in notepad, it does not show the lone LF character at all, so it looks like it all runs together on one line. So, in the CSV file, even though notepad doesn't show it, it actually looks like this:
' 1,"This is nothing but the Example to explanation{LF}It results wrong",testing example{CR}{LF}
According to the MSDN documentation on the StreamReader.Readline method:
A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r"), or a carriage return immediately followed by a line feed ("\r\n").
Therefore, when you call ReadLine, it will stop reading at the end of the first line in a multi-line cell. To avoid this, you would need to use a different "read" method and then split on CR/LF pairs rather than on either individually.
However, this isn't the only issue you will run into with reading CSV files. For instance, you also need to properly handle the way quotation characters in a cell are escaped in CSV. In such cases, unless it's really necessary to implement it in your own way, it's better to use an existing library to read the file. In this case, Microsoft provides a class in the .NET framework that properly handles reading CSV files (including ones with multi-line cells). The name of the class is TextFieldParser and it's in the Microsoft.VisualBasic.FileIO namespace. Here's the link to a page in the MSDN that explains how to use it to read a CSV file:
http://msdn.microsoft.com/en-us/library/cakac7e6
Here's an example:
Using reader As New TextFieldParser("my csv file Path")
reader.TextFieldType = FieldType.Delimited
reader.SetDelimiters(",")
While Not reader.EndOfData
Try
Dim fields() as String = reader.ReadFields()
' Process fields in this row ...
Catch ex As MalformedLineException
' Handle exception ...
End Try
End While
End Using

Avoiding 'End Of File' errors

I'm trying to import a tab delimited file into a table.
The issue is, SOMETIMES, the file will include an awkward record that has two "null values" and causes my program to throw a "unexpected end of file".
For example, each record will have 20 fields. But the last record will have only two fields (two null values), and hence, unexpected EOF.
Currently I'm using a StreamReader.
I've tried counting the lines and telling bcp to stop reading before the "phantom nulls", but StreamReader gets an incorrect count of lines due to the "phantom nulls".
I've tried the following code to get rid of all bogus code (code borrowed off the net). But it just replaces the fields with empty spaces (I'd like the result of no line left behind).
Public Sub RemoveBlankRowsFromCVSFile2(ByVal filepath As String)
If filepath = DBNull.Value.ToString() Or filepath.Length = 0 Then Throw New ArgumentNullException("filepath")
If (File.Exists(filepath) = False) Then Throw New FileNotFoundException("Could not find CSV file.", filepath)
Dim tempFile As String = Path.GetTempFileName()
Using reader As New StreamReader(filepath)
Using writer As New StreamWriter(tempFile)
Dim line As String = Nothing
line = reader.ReadLine()
While Not line Is Nothing
If Not line.Equals(" ") Then writer.WriteLine(line)
line = reader.ReadLine()
End While
End Using
End Using
File.Delete(filepath)
File.Move(tempFile, filepath)
End Sub
I've tried using SSIS, but it encounters the EOF unexpected error.
What am I doing wrong?
If you read the entire file into a string variable (using reader.ReadToEnd()) do you get the whole thing? or are you just getting the data up to those phantom nulls?
Have you tried using the Reader.ReadBlock() function to try and read past the file length?
At our company we do hundreds of imports every week. If a file is not sent in the correct, agreed to format for our automated process, we return it to the sender. If the last line is wrong, the file should not be processed because it might be missing information or in some other way corrupt.
One way to avoid the error is to use ReadAllLines, then process the array of file lines instead of progressing through the file. This is also a lot more efficient than streamreader.
Dim fileLines() As String
fileLines = File.ReadAllLines("c:\tmp.csv")
...
for each line in filelines
If trim(line) <> "" Then writer.WriteLine(line)
next line
You can also use save the output lines in the same or a different string array and use File.WriteAllLines to write the file all at once.
You could try the built-in .Net object for reading tab-delimited files. It is Microsoft.VisualBasic.FileIO.TextFileParser.
This was solved using a bit array, checking one bit at a time for the suspect bit.