How to Remove Line Break in String

前端 未结 13 2163
旧时难觅i
旧时难觅i 2020-12-09 01:16

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 Rig         


        
13条回答
  •  北海茫月
    2020-12-09 01:39

    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
    

提交回复
热议问题