VBCRLF Trim

AlexanderBB

Well-known Member
Joined
Jul 1, 2009
Messages
2,072
Office Version
  1. 2019
  2. 2010
Platform
  1. Windows
I have a need to remove any leading or trailing VBCRLF characters from a string.
What I have is this, but there may be a better way ?
VBA Code:
If Len(str) > 0 Then
    Do
        Select Case Asc(Right(str, 1))
            Case 13, 10
                str = Left(str,Len(str)-1)
            Case Else
                Exit Do
        End Select
    Loop Until Len(str) = 0
End If
TheTrim = str
Then do something similar to the start of the string.
But I wonder if that's the best/fastest approach ?
Must also handle a single CR or LF.
 

Excel Facts

Pivot Table Drill Down
Double-click any number in a pivot table to create a new report showing all detail rows that make up that number
Not suggesting this is necessarily better but you could remove all leading & trailing instances of both characters at once rather than dealing with one character at a time and one end at a time.

VBA Code:
Sub Test()
  Dim RX As Object
  Dim str As String, TheTrim As String
  
  str = Chr(10) & Chr(13) & Chr(10) & "abc" & Chr(13) & Chr(10) & "def" & Chr(13)
  
  Set RX = CreateObject("VBScript.RegExp")
  RX.Global = True
  RX.Pattern = Replace("(^[#]*)|([#]*$)", "#", Chr(10) & Chr(13))
  TheTrim = RX.Replace(str, "")
End Sub
 
Upvote 0
Solution
If the value is in a cell AFAIK, you only would need to test for vblf (ascii 10). Same thing as if you were to pass the cell value to a string variable.
 
Upvote 0
That's very good , thank you. It feels much more efficient
The string is extracted from a comment (Note) and should never have a CR, I was just making sure.
Will test a few with just vblf.

Much appreciated.
 
Upvote 0

Forum statistics

Threads
1,223,905
Messages
6,175,297
Members
452,633
Latest member
DougMo

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top