'Purpose : Trims trailing a leading characters from a string buffer
'Inputs : sValue The string to trim
' sRemove The character/s to remove from the start/end of the sValue
' [bRtrim] If True removes any matching right hand side chars
' [bLtrim] If True removes any matching left hand side chars
' [eCompare] The method of comparison
'Outputs : Returns the string trimed from the specified characters
'Notes : Trim2("aaaaaBBBBCCCaaaa", "a") returns "BBBBCCC"
Function Trim2(ByVal sValue As String, sRemove As String, Optional bRtrim As Boolean = True, Optional bLTrim As Boolean = True, Optional eCompare As VbCompareMethod = vbBinaryCompare) As String
Dim lPos As Long, lLastChar As Long, lLenRemove As Long
On Error GoTo ErrFailed
lLenRemove = Len(sRemove)
If lLenRemove > 0 And Len(sValue) > 0 Then
If bLTrim Then
'Remove the left hand chars
lPos = 1 - lLenRemove
lLastChar = 1 - lLenRemove
'Loop finding the chars to replace
Do
lPos = InStr(lPos + lLenRemove, sValue, sRemove, eCompare)
If lPos = lLastChar + lLenRemove Then
lLastChar = lPos
Else
'Found all the matching characters
Exit Do
End If
Loop
If lLastChar Then
sValue = Mid$(sValue, lLastChar + lLenRemove)
End If
End If
If bRtrim = True And Len(sValue) > 0 Then
'Remove the right hand chars
lPos = Len(sValue) + 1
lLastChar = lPos
'Loop finding the chars to replace
Do
lPos = InStrRev(sValue, sRemove, lPos - 1, eCompare)
If lPos = lLastChar - lLenRemove Then
lLastChar = lPos
Else
'Found all the matching characters
Exit Do
End If
Loop
If lLastChar Then
sValue = Left$(sValue, lLastChar - 1)
End If
End If
End If
Trim2 = sValue
Exit Function
ErrFailed:
Debug.Print "Error in Trim2: " & Err.Description
Debug.Assert False
End Function
No comments:
Post a Comment