58

I want to Remove the Line Break from the string if my string Ends with Line Break.

Sub linebreak(myString)
    If Len(myString) <> 0 Then
        If Right$(myString, 1) = vbCrLf Or Right$(myString, 1) = vbNewLine Then myString = Left$(myString, Len(myString) - 1)
    End If
End Sub
Zoe
  • 27,060
  • 21
  • 118
  • 148
Code Hungry
  • 3,930
  • 22
  • 67
  • 95

14 Answers14

98

Summary

str = Replace(str, vbLf, "")

This code takes all the line break's out of the code

if you just want the last one out:

If Right(str, 1) = vbLf Then str = Left(str, Len(str) - 1)

is the way how you tried OK.


Background Info

line feed = ASCII 10, form feed = ASCII 12 and carriage return = ASCII 13. Here we see clearly what we all know: the PC comes from the (electric) typewriter.

vbLf is Chr (10) and means that the cursor jumps one line lower (typewriter: turn the roller)

vbCr is Chr (13) and means the cursor jumps to the beginning (typewriter: pull back the roll)

In DOS, a line break is always VBCrLf or Chr (13) & Chr (10), in files anyway, but e.g. also with the text boxes in VB.

In an Excel cell, on the other hand, a line break is only VBLf, the second line then starts at the first position even without vbCr. With vbCrLf then go one cell deeper.

So it depends on where you read and get your String from. if you want to remove all the vbLf (Chr(10)) and vbCr (Char(13)) in your string, you can do it like this:

strText = Replace(Replace(strText, Chr(10), ""), Chr(13), "")

If you only want t remove the Last one, you can test on do it like this:

If Right(str, 1) = vbLf or Right(str, 1) = vbCr Then str = Left(str, Len(str) - 1)
StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Moosli
  • 3,140
  • 2
  • 19
  • 45
  • 7
    Not sure why this answer has so many votes... it leaves a bunch of `vbCr` characters in the string. – Mathieu Guindon Aug 10 '17 at 17:07
  • I am working with a `filesystemobject` where I am writing lists for comboboxes, whenever I recall the textfile it mysteriously adds a paragraph symbol at the end. (in fact it added them all over the place, but this code removed ALL except..^) this doesn't seem to rid me of that last one at the end of the text. Chr(13) leaves some however. In the actual textfile these characters are completely invisible, my text is ";" separated... there isn't even a space, but there is somehow a linebreak. Thanks for this, just wish it got that last one!! x.X – Reverus Mar 03 '18 at 21:01
  • 1
    @Reverus i updated my Code, hope this will help you.can help you. – Moosli Mar 04 '18 at 13:03
  • 1
    @Mat'sMug Thanks for the hint, i Updated my Answer and hope it's a better Explanation now. – Moosli Mar 04 '18 at 13:04
  • Thanks! Works great, I was trying vbCrLf without success – John W. Jul 01 '22 at 18:35
  • Old post but worth noting, vbCr works in most cases instead of vbLf (which is rare), so either use: Replace("your_string", vbCr, "") or check for both the vbCr and vbLf (vbNewLine). HTH. – Eddie Kumar Aug 08 '23 at 09:57
38

vbCrLf and vbNewLine are actualy two characters long, so change to Right$(myString, 2)

Sub linebreak(myString)
    If Len(myString) <> 0 Then
        If Right$(myString, 2) = vbCrLf Or Right$(myString, 2) = vbNewLine Then 
            myString = Left$(myString, Len(myString) - 2)
        End If
    End If
End Sub
chris neilsen
  • 52,446
  • 10
  • 84
  • 123
  • 1
    _"vbCrLf and vbNewLine are actualy two characters long"_ ... Wow! I've been coding with VBA a while and never noticed that. I just found some bugs in my own apps related to this. Thanks! – ChrisB May 15 '19 at 00:04
15

Try with the following line:

CleanString = Application.WorksheetFunction.Clean(MyString)
Gonzalo Garcia
  • 6,192
  • 2
  • 29
  • 32
joe
  • 159
  • 1
  • 2
11

As you are using Excel you do not need VBA to achieve this, you can simply use the built in "Clean()" function, this removes carriage returns, line feeds etc e.g:

=Clean(MyString)
Matt Donnan
  • 4,933
  • 3
  • 20
  • 32
  • 2
    This removes _all_ non printables, not line breaks from the end. – chris neilsen Apr 05 '12 at 09:39
  • @chrisneilsen Apologies, I thought Excel represents these characters as a square symbol, and the clean method removes those? – Matt Donnan Apr 05 '12 at 12:17
  • woo! I understand that this is a nuclear option. But in my case it worked to get rid of that last symbol!!! :D nice work! (see @Moosli 's comments for my first comment) – Reverus Mar 03 '18 at 21:07
5

Clean function can be called from VBA this way:

Range("A1").Value = Application.WorksheetFunction.Clean(Range("A1"))

However as written here, the CLEAN function was designed to remove the first 32 non-printing characters in the 7 bit ASCII code (values 0 through 31) from text. In the Unicode character set, there are additional nonprinting characters (values 127, 129, 141, 143, 144, and 157). By itself, the CLEAN function does not remove these additional nonprinting characters.

Rick Rothstein have written code to handle even this situation here this way:

Function CleanTrim(ByVal S As String, Optional ConvertNonBreakingSpace As Boolean = True) As String
  Dim X As Long, CodesToClean As Variant
  CodesToClean = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, _
                       21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 127, 129, 141, 143, 144, 157)
  If ConvertNonBreakingSpace Then S = Replace(S, Chr(160), " ")
  For X = LBound(CodesToClean) To UBound(CodesToClean)
    If InStr(S, Chr(CodesToClean(X))) Then S = Replace(S, Chr(CodesToClean(X)), "")
  Next
  CleanTrim = WorksheetFunction.Trim(S)
End Function
Rocketq
  • 5,423
  • 23
  • 75
  • 126
5

just this:

str = Replace(str, vbCrLf, "")
decas
  • 73
  • 1
  • 5
3
mystring = Replace(mystring, Chr(10), "")
user3117021
  • 55
  • 1
  • 2
1

Replace(yourString, vbNewLine, "", , , vbTextCompare)

Divyank Sabhaya
  • 265
  • 3
  • 5
1

I know this post is very old but I could not find anything that would do this. So I finally put this together from all the forums.

This will remove All line breaks from the left and right, and removes any blank lines. Then Trim it all to look good. Alter as you see fit. I also made one that removes All Line Breaks, if interested. TY

    Sub RemoveBlankLines()
    Application.ScreenUpdating = False
    Dim rngCel As Range
    Dim strOldVal As String
    Dim strNewVal As String

    For Each rngCel In Selection
        If rngCel.HasFormula = False Then
            strOldVal = rngCel.Value
            strNewVal = strOldVal
            Debug.Print rngCel.Address

            Do
            If Left(strNewVal, 1) = vbLf Then strNewVal = Right(strNewVal, Len(strNewVal) - 1)
            If strNewVal = strOldVal Then Exit Do
                strOldVal = strNewVal
            Loop

            Do
            If Right(strNewVal, 1) = vbLf Then strNewVal = Left(strNewVal, Len(strNewVal) - 1)
            If strNewVal = strOldVal Then Exit Do
                strOldVal = strNewVal
            Loop

            Do
            strNewVal = Replace(strNewVal, vbLf & vbLf, "^")
            strNewVal = Replace(strNewVal, Replace(String(Len(strNewVal) - _
                        Len(Replace(strNewVal, "^", "")), "^"), "^", "^"), "^")
            strNewVal = Replace(strNewVal, "^", vbLf)

            If strNewVal = strOldVal Then Exit Do
                strOldVal = strNewVal
            Loop

            If rngCel.Value <> strNewVal Then
                rngCel = strNewVal
            End If

        rngCel.Value = Application.Trim(rngCel.Value)
        End If
    Next rngCel
    Application.ScreenUpdating = True
End Sub
Mouthpear
  • 199
  • 1
  • 3
  • 13
  • rngCel. HasFormula not found, please fix it. – WebComer Nov 26 '18 at 22:16
  • WebComer the HasFormula is a basic function. There is nothing I can fix if your PC does not recognize it. https://learn.microsoft.com/en-us/office/vba/api/excel.range.hasformula – Mouthpear Nov 30 '18 at 08:41
  • @Albin Do you mean comments inside the code to tell you what each line does? – Mouthpear Jan 09 '20 at 22:20
  • @Mouthpear yeah – Albin Jan 11 '20 at 13:37
  • @Albin yeah that be nice but I'm not much good at coding. I barely got it work (and does what calls for in this thread awesomely?) But I hardly understand it myself even tho I'm the one who put it together. I have to put those pause breaks in code in VBA to break it down and see how it works and what it is doing at each line. That how I learn/figure out how the codes work then I modify. I still don't know how it works but it works. I just left it here just in case it works for others. – Mouthpear Jan 13 '20 at 01:05
0
Private Sub Form_Load()
    Dim s As String

    s = "test" & vbCrLf & "this" & vbCrLf & vbCrLf
    Debug.Print (s & Len(s))

    s = Left(s, Len(s) - Len(vbCrLf))
    Debug.Print (s & Len(s))
End Sub
Pang
  • 9,564
  • 146
  • 81
  • 122
0

None of the other answers (with one exception, see my edit) handle the case where there are multiple trailing carriage returns. If the goal is to make a function similar to "Trim" that removes carriage returns as well as spaces, you'll probably want it to be robust enough to remove as many as there are and not just one. Also, I'd recommend avoiding the use of the "Left" or "Right" functions in VBA since they do not exist in VB.Net. It may be necessary at some point to convert an Office VBA Macro to a VSTO COM Add-In so it's a good habit to avoid the use of functions that only exist in VBA.

Function RemoveTrailingWhiteSpace(s As String) As String
    RemoveTrailingWhiteSpace = s
    Dim StrLen As Long
    StrLen = Len(RemoveTrailingWhiteSpace)
    While (StrLen > 0 And (Mid(RemoveTrailingWhiteSpace, StrLen) = vbCr Or Mid(RemoveTrailingWhiteSpace, StrLen) = vbLf) Or Mid(RemoveTrailingWhiteSpace, StrLen) = " ")
        RemoveTrailingWhiteSpace = Mid(RemoveTrailingWhiteSpace, 1, StrLen - 1)
        StrLen = Len(RemoveTrailingWhiteSpace)
    Wend
End Function

Edit: I should clarify that there is another answer listed here that trims carriage returns and white space from both ends of the string, but it looked far more convoluted. This can be done fairly concisely.

0

No one has ever suggested a RegExp solution. So here is one:

Function TrimTrailingLineBreak(pText)
    Dim oRE: Set oRE = New RegExp: oRE.Global = True
    oRE.Pattern = "(.*?)(\n|(\r\n)){1}$"
    TrimTrailingLineBreak = oRE.Replace(pText, "$1")
End Function

It captures and returns everything up until a single ({1}) trailing new line (\n), or carriage return & new line (\r\n), at the end of the text ($).
To remove all trailing line breaks change {1} to *.
And to remove all trailing whitespace (including line breaks) use oRE.Pattern = "(.*?)\s*$".

Howd
  • 51
  • 4
0

I hope this'll do . or else, may ask me directly

  
Sub RemoveBlankLines()
    Application.ScreenUpdating = False
    Dim rngCel As Range
    Dim strOldVal As String
    Dim strNewVal As String

    For Each rngCel In Selection
        If rngCel.HasFormula = False Then
            strOldVal = rngCel.Value
            strNewVal = strOldVal
            Debug.Print rngCel.Address

            Do
            If Left(strNewVal, 1) = vbLf Then strNewVal = Right(strNewVal, Len(strNewVal) - 1)
            If strNewVal = strOldVal Then Exit Do
                strOldVal = strNewVal
            Loop

            Do
            If Right(strNewVal, 1) = vbLf Then strNewVal = Left(strNewVal, Len(strNewVal) - 1)
            If strNewVal = strOldVal Then Exit Do
                strOldVal = strNewVal
            Loop

            Do
            strNewVal = Replace(strNewVal, vbLf & vbLf, "^")
            strNewVal = Replace(strNewVal, Replace(String(Len(strNewVal) - _
                        Len(Replace(strNewVal, "^", "")), "^"), "^", "^"), "^")
            strNewVal = Replace(strNewVal, "^", vbLf)

            If strNewVal = strOldVal Then Exit Do
                strOldVal = strNewVal
            Loop

            If rngCel.Value <> strNewVal Then
                rngCel = strNewVal
            End If

        rngCel.Value = Application.Trim(rngCel.Value)
        End If
    Next rngCel
    Application.ScreenUpdating = True
End Sub
Zhivenia
  • 1
  • 1
-1

I had the exact same issue. I made a separate function I can call easily when needed:

Function removeLineBreakIfAtEnd(s As String) As String
    If Right(s, 1) = vbLf Then s = Left(s, Len(s) - 2)
    removeLineBreakIfAtEnd = s
End Function

I found that I needed to check the last character only and do -2 to remove the line break. I also found that checking for vbLf was the ONLY way to detect the line break. The function can be called like this:

Sub MainSub()
    Dim myString As String
    myString = "Hello" & vbCrLf
    myString = removeLineBreakIfAtEnd(myString)
    MsgBox ("Here is the resulting string: '" & myString & "'")
End Sub
SendETHToThisAddress
  • 2,756
  • 7
  • 29
  • 54