Replace CarriageReturn Using Replace in VBA - vba

I am relatively new to VBA and want to accomplish something pretty simple but am confused as to why this is not working. I am reading in lines from a file and if opened in notepad++, each line has a CRLF at the end. I would like to just remove the CR. In notepad++ I can do a replaceall, replacing CRLF with LF and things work great. However, the test I have in VBA right now is not doing this correctly. Below is an example of a string I'm dealing with in Notepad++:
Summary - I went for a walk in the parkCRLF
I want the string to become, Summary - I went for a walk in the parkLF
I am writing out to a file as a test in order to see if its working. Below is my code:
Do While Not txtStream.AtEndOfStream
str = txtStream.ReadLine
edited = Replace(str, Chr(13) & Chr(10), Chr(10))
stream.WriteLine (edited)
Loop
txtStream.Close
The code is being executed without error but the CRLF is still at the end of each line in the newly written file...Maybe I'm missing something obviously but the replace does not seem to be picking up on what I'm searching for. Any help or advice on this would be greatly appreciated!
Even figuring out if the end of the line ends with a CRLF would be a step in the right direction at this point.
Thank you.

WriteLine automatically places an end of line after your string
You should replace it with #Mark's suggestion: stream.Write(edited)
This performs better:
stream.Write(Replace(txtStream.ReadAll, vbCrLf, vbLf))
or
stream.Write(Replace(txtStream.ReadAll, vbCr, vbLf))
.
Details about ReadAll

You are reading a line so it will remove the new line characters. Your replace statement has nothing to do. You are then writing a line which will add new line characters.
Also, you aren't closing the output stream in the code sample you provided.
You will want something like this:
Do While Not txtStream.AtEndOfStream
str = txtStream.ReadLine
stream.Write str & Chr(10)
Loop
txtStream.Close
stream.Close

Related

VBA/VB6 Not Recognizing VbCrLf

Happy Friday everyone!
I would appreciate some direction on this.
I have processed an .html file as follows:
strStringToClean = Replace(strStringToClean, vbCr, vbCrLf)
strStringToClean = Replace(strStringToClean, vbLf, vbCrLf)
strStringToClean = Replace(strStringToClean, cr, vbCrLf)
strStringToClean = Replace(strStringToClean, lf, vbCrLf)
strStringToClean = Replace(strStringToClean, """""", """")
(as you can see, throwing in some redundant lines in a effort to trouble shoot)
When the file is close and then inspected in NotePad++ I see "CR LF" at the end of every line (the original file has only "LF". However, when I open it for input (Open MyFile for Input as #1), everything is pulled back as a single line, making it almost impossible to parse.
Any thoughts would be greatly appreciated.
Thanks!
Trip
Trying to remember the solution a few days on now... However, if I remember correctly, the issue was that I was writing the output using "Write #1, myString" as opposed to "Print #1, myString". In my experience, "Write" will result in VbCrLf not working properly while "Print" will.

Indentify line breaks in excel VBA

I'm trying to identify a cell has line breaks(not the menu bar cell option, actual multiple lines through alt+enter), and extract each line separatedely
I have tried both
InStr(str, "\n") < 0
and
Split(str, "\n")
But doesn't seem to be working
VBA is not C# ("\n"). Line breaks you'll find on: vbCr or vbLf or vbCrLf constants.
For further information, please see:
vbCr
vbLf
vbCrLf
[EDIT]
Points to Mat's Mug answer! I forgot about vbNewLine constant.
There are no escape sequences in VBA. Use the built-in vbNewLine constant instead for the equivalent:
hasLineBreaks = InStr(str, vbNewLine) > 0
Per MSDN, vbNewline returns a Platform-specific new line character; whichever is appropriate for current platform, that is:
Chr(13) + Chr(10) [on Windows] or, on the Macintosh, Chr(13)
So you don't need to work with ASCII character codes, or even with their respective built-in constants.
Except Excel will strip CR chars from cell and shape contents, and this has nothing to do with VBA (the CR chars would be stripped all the same and "\n" wouldn't work for correctly reading that Excel data in C#, Javascript, or Python either) and everything to do with the context of where the string came from.
To read "line breaks" in a string with the CR chars stripped, you need to look for line feed chars in the string (vbLf).
But if you systematically treat the line feed character as a line ending, you'll eventually run into problems (esp.cross-platform), because ASCII 10 all by itself isn't an actual line break on either platform, and you'll find ASCII 13 characters in strings you thought you had stripped line breaks from, and they'll still properly line-break on a Mac, but not on Windows.
Consider either:
Split(str, Chr(10))
or
Split(str, Chr(13))
You may need to try both if the data has been imported from external source.

line input not working as expected in 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).

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 use Split to tokenize text file using the new line character as a delimiter

Using VBA how would one go about using the VBA.Split method to tokenize text file using the new line character as a delimiter?
The following don't seem to work:
Split(myText, "\n")
Split(myText, vbCrLf)
Split(myText, vbNewLine)
After a little investigation turns out the answer is:
Split(data, vbLf)
If you are working within VBA, you don't need all the VBA tags:
Split(data, vbLf)
Another way to get it work is
split(myText,Chr(13) + Chr(10))
Found the anser on chandoo:
Split(ActiveCell.Value, Chr(10))