How to detect a line break in Excel through VBA - excel

I'm trying to find the carriage return\line break in various cells, by iterating over them and running the InStr function against the text in each of those cells. The below query is finding the line break correctly in most cells, but is failing in one of those cells.
The line break in those cells was added the same for all of them, and that is by hitting Alt+Enter.
Below is the function I am using:
InStr(startlocation, text, vbLf)
I also tried all of the below, but to no avail:
InStr(startlocation, text, Chr(10)) 'this seems to be identical in results to using vbLf
InStr(startlocation, text, Chr(13)) 'No results with this
InStr(startlocation, text, ALT + 10) 'I see this returning some results sometimes, not exactly sure for which character though
InStr(startlocation, text, vbCrLf) 'No results with this
Is there any other way to represent line break so I add it to my query?

The line break in cells, which is created with Alt + Enter is a vbLf.
Therefore the following should work.
InStr(startlocation, text, vbLf)
If it doesn't work that means you did something else wrong.
If you have the following data in cell A1 (Alt + Enter after 1 and 2)
Then InStr(1, Range("A1"), vbLf) returns 2.
For example you can use …
Dim ArrLines As Variant
ArrLines = Split(Range("A1"), vbLf)
to split these lines into an array like …
ArrLines(0) is 1
ArrLines(1) is 2
ArrLines(2) is 3

As others have confirmed, vbLf was indeed the correct character for identifying the line break introduced by ALT + Enter. My issue turned out to be caused by how the content of text was ending one character before the line break, therefore the InStr(startlocation, text, vbLf) on that string was not finding the line break. Extending text (which was created using the Mid function) by 1 took care of the issue. So:
Instead of: text = Mid(entryvalue, delimeterlocation, Len(entryvalue) - delimeterlocation)
I did this: text = Mid(entryvalue, delimeterlocation, Len(entryvalue) - delimeterlocation + 1)

Related

I have text in separate lines inside same box, How to make it all in one line

Some of my text are in different lines inside same cell. I want them in single line. How do I bring them in single line ?
Example:
first cell contains:
Hi Ram, I want to go to movie today.
Are you willing to join?
If yes, let me know early.
Example:
Expected output:
Hi Ram, I want to go to movie today.Are you willing to join?If yes, let me know early.
New line in a cell A1 caused by alt+Enter for example, may be removed using a formula such as:
=SUBSTITUTE(A1,CHAR(10)," ")
Where A1 is the cell containing the text to be changed. You can enter the formula above in a different cell of course.
The parameter " " indicates 1 space to replace the line break. You could use any other character.
Another type of line break is CHAR(13). You can remove CHAR(13) using the same function again:
=SUBSTITUTE(SUBSTITUTE(A1, CHAR(13)," "), CHAR(10), " ")
In case you had some spaces already before the new-line character, you need to wrap the above formula in a TRIM function like so:
=TRIM(SUBSTITUTE(A1,CHAR(10)," "))
OR
=TRIM(SUBSTITUTE(SUBSTITUTE(A1,CHAR(13)," "),CHAR(10)," "))
Always make a copy of your file before you apply formulas that could change the data.
Note-1:
char(13) is officially called "carriage return" and char(10) is called "line feed".
CHAR(10) returns a line break on Windows, and CHAR(13) returns a line break on the Mac. This answer is for Windows. You can't visually see it but you can see its effect.
Note-2:
As #kojow7 answered, a text wrap can cause the text to appear on more than 1 line depending on the cell width and the text length. This answer does not resolve this case.
Related discussion can be found here: Remove line breaks from cell.
Two things you may need to fix here: 1) Line breaks and 2) Text Wrapping
To fix line breaks:
Select the cells that need to be changed
Press CTRL+H to open Search and Replace
In the Find box type CTRL+J to insert the line break character (it may look like nothing was inserted in the field, but it does insert a line break)
Decide whether to replace the line breaks with a space or with nothing
Press Replace All
To turn off text wrapping:
Select the cells that need to be changed
Go to the Home Tab
In the Alignment Group check to see if the Wrap Text button is clicked.
If it is, click on it again to deselect it.
Depending on your situation, you may need to fix either one or both of these.
Depending on your document it might contain linefeeds or carriage returns or BOTH.
Alexander Frolov (https://www.ablebits.com/office-addins-blog/2013/12/03/remove-carriage-returns-excel/) has written a very good blog post about different technics of finding and removing linebreaks in an Excel file. We will use the “macro way” of doing that – as it is the one that works either on Windows AND Mac. The search replace method offered here too will not work on Mac but on windows.
Add the below Macro to your document (slighlty modified from the original)
Change the value of “ReplaceWith” from ” ” (space) to anything you like a linebreak to be replaced with.
E.g. ReplaceWith = “-” will result in “Line1-Line2-Line3”
Run the Macro (Extras > Macro) while all cells are selected.
Sub RemoveCarriageReturns()
ReplaceWith = " "
LinefeedChar = Chr(10)
Dim recordRange As Range
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
For Each recordRange In ActiveSheet.UsedRange
If 0 < InStr(recordRange, LinefeedChar) Then
recordRange = Replace(recordRange, LinefeedChar, ReplaceWith)
End If
Next
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
If your separate lines are not gone by now please change "LinefeedChar" from "Chr(10)" to "Chr(13)" and run it again

How to reverse search in Excel?

I have a text in a worksheet like:
The girl is very beautiful
I want a formula to perform a search from right to left for the word "very", and if found then extract it to some other region of the sheet.
Note: Purpose of doing reverse search is because I want to implement it in my workbook which requires reverse search.
At least, say me how to revert the text like this :
beautiful very is girl The
Then I can do a normal search. I don't know VBA so please give some formula.
VBA Function to reverse the words in text:
Public Function StrReverse(strIn As String, Optional Delimiter As String = " ") As String
'Reverse the words in 'StrIn', split on a "Space" unless 'Delimiter' is specified
Do While InStrRev(strIn, Delimiter) <> 0
StrReverse = StrReverse & Delimiter & Right(strIn, Len(strIn) - InStrRev(strIn, Delimiter))
strIn = Trim(Left(strIn, InStrRev(strIn, Delimiter) - 1))
Loop
StrReverse = Trim(StrReverse & Delimiter & strIn)
If Left(StrReverse, 1) = Delimiter Then StrReverse = Right(StrReverse, Len(StrReverse) - 1)
End Function
For example, if cell A1 contains:
The girl is very beautiful
...then you could enter in another cell:
=StrReverse(A1)
...which would return:
beautiful very is girl The
To add a custom VBA function to a workbook:
Copy the code for the function you want to add to Excel (from above).
In an Excel, workbook, press Alt + F11 to open the VBA Editor (VBE).
Press Alt + I M to insert a new module.
Press Ctrl + V to paste in the code.
Press Alt + F C to return to Excel.
Edit #1:
Added optional delimiter to function above (defaults to a " " space).
Also, FindReverse (below), which allows VBA's (little-known) InStrRev function to be used on worksheets.
Public Function FindReverse(StringCheck As String, StringMatch As String, _
Optional Start As Long = -1) As Long
'Returns the position number of the last occurrence of 'Stringmatch"
'within StringCheck', Optionally specify the position number from the
'end to begin the search. (-1 = Begin at the end)
FindReverse = InStrRev(StringCheck, StringMatch, Start)
End Function
Edit #2:
LOL # Myself ... I'm always telling people not to try to recreate functionality that's already built into MS Office, and it seems that I unwittingly did the same thing -- even giving it the same as the existing VBA Function.
Built-in VBA function:
I realize that it's not identical functionality as the StrReverse function I wrote (above) but I suspect it also could have solved OP's original inquiry...
Nonetheless, I am really surprised that VBA even allows a custom function to have the same name as a built-in function!
How to confuse VBA:

Count commas in line of text file

I have a text file and I'm trying to count the number of commas in the first line of the file using excel VB and then do an action if there are 3 - but something is wrong. When I use the replace method (commented out in this example below) the macro fails, and when I use the Split method it ALWAYS does the action, no matter what value I add in place of 3.
'Load txt file into array
Open FilePath For Input As #1
dataArray = Split(Input$(LOF(1), #1), vbLf)
Close #1
'Test first line if it has three commas
If Len(dataArray(0).value) - Len(Replace(dataArray(0).value, ",", "")) = 3 Then
'If dataArray(0).Split(",").Length = 3 Then
'Add comma to start of strings
For i = LBound(dataArray) To UBound(dataArray)
dataArray(i) = "," & dataArray(i)
Next i
The .value appears to be the problem. VBA doesn't have properties the same way .NET does.
Replace your uncommented out IF statement with this:
If Len(dataArray(0)) - Len(Replace(dataArray(0), ",", "")) = 3 Then

Excel INSTR to find hard return in cell

I have a spreadsheet where the Item description is a variable length but always finishes with a "hard return" to force a wrapped line in the cell. I need to copy the first line of the cell into another cell.
Can I use INSTR to find the first instance of a hard return (invisible character) and then copy the first N-1 characters?
For example:
Dell PowerEdge R720XD
Chassis (Max of ......
OR
Dell OptiPlex 7010 Minitower
Intel Core.............
In all cases I need to copy the first line of the text in the cell, irrespective of length.
Any ideas how I could do this??
Yes, you can easily do this
strShort = Left(strLong, InStr(strLong, vbCrLf) - 1)
Some times (eep. when sourced from a Unix system), you might have to replace vbCrLf (carriage Return, LineFeed) with a vbLf only.
If you are not sure if it contains an Enter, this code will do
strShort = IIf(InStr(strLong, vbCrLf), Left(strLong, InStr(strLong, vbCrLf) - 2), strLong)
Depending on the type of line break you can do it this way:
InStr(Range("A1").Text, vbLf)
InStr(Range("A1").Text, vbCr)
InStr(Range("A1").Text, vbCrLf)
to get the text before the line break:
Left(Range("A1").Text, InStr(Range("A1").Text, vbLf) - 1)
to get the text after the line break:
Right(Range("A1").Text, InStr(Range("A1").Text, vbLf))
I was not able to add a comment to Ripster's code below. I needed a reputation of 50; mine's only 36, but that's really where this comment should go instead of a separate answer.
It seems to me that the last bit of Ripster's code,
Right(Range("A1").Text, InStr(Range("A1").Text, vbLf))
should be,
Right(Range("A1").Text, (Len(Range("A1")-InStr(Range("A1").Text, vbLf)) - 1)
And finally to regenerate the string without the break
strString = Left(Range("A1").Text, InStr(Range("A1").Text, vbLf) - 1) & Right(Range("A1").Text, (Len(Range("A1")-InStr(Range("A1").Text, vbLf)) - 1)
A note to the moderators : Please review this. I still consider mysefl as a beginner to VBA and my logic could be wrong.
my solution is:
strString = Replace(strString, vbLf, "")
It is useful even if the string contains more than one line brakes.

Turn Excel line break into <br>

A client sent me a huge list of product name and descriptions. The Description cells have text wrap and many line breaks. I need to import this into a MySQL which I do through Navicat Premium.
The problem is that the description cell is used as the HTML description of each product page.
Is there a way to replace Excel's line break with the <br> either in the same Excel file or by a php function?
A little bit of ASCII coding will go a long way.
Set up the find/replace dialogue (Ctrl-H). In the Find field, hold down the Alt key and type 010 from the numeric key pad. (This lets you find a linefeed character.) In the replace field, put your <br>.
or use a VBA function to replace the carriage returns in a string
Insert a MODULE and paste this
Function LineFeedReplace(ByVal str As String)
dim strReplace as String
strReplace = "<br>"
LineFeedReplace = Replace(Replace(Replace(Replace(Replace(Replace(str, Chr(10), strReplace), Chr(13), strReplace), vbCr , strReplace), vbCrLf, strReplace), vbLf, strReplace), vbNewLine, strReplace)
End Function
If cell A1 contains a string with a linefeed then =LineFeedReplace(A1) will return the string with all linefeeds set to <br>
First make sure you account for both CR and LF which tend to come together. The codes for these are 0013 and 0010 and so you will need a formula that allows you to clean both. I used this formula successfully =SUBSTITUTE(A3,CHAR(13),"<br>") to convert a cell of long text in excel replacing invisible breaks with the 'br' tag. Since you can't tell exactly what kind of line break you have you can also try it with 0010 or =SUBSTITUTE(A3,CHAR(10),"<br>")

Resources