How to Remove Line Break in String

前端 未结 13 2162
旧时难觅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条回答
  •  -上瘾入骨i
    2020-12-09 01:29

    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.

提交回复
热议问题