VB and VBA Users Source Code: Ensuring a string always starts or ends with specific characters
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
VB/VBA Source Code
Ensuring a string always starts or ends with specific characters
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Friday, August 26, 2005
Hits:
2438
Category:
Visual Basic General
Article:
Below are two simple routines that ensure a string always starts with or ends with some particular text. 'Purpose : Ensures the specified string always starts with a specific text. 'Inputs : sText The text to check the starting characters of. ' sStartWith The text to ensure is a the beginning of sText parameter. ' [bIgnoreCase] If true performs a case insensitive comparison, else does not. 'Outputs : The specified string, starting with the sStartWith parameter. 'Author : Andrew Baker 'Date : 25/03/2005 'Notes : Public Function StringStartWith(ByRef sText, ByRef sStartWith As String, Optional bIgnoreCase As Boolean = True) As String Dim bPrepend As Boolean If Len(sStartWith) Then If bIgnoreCase Then If UCase$(Left$(sText, Len(sStartWith))) <> UCase$(sStartWith) Then 'String doesn't start with specified text bPrepend = True End If Else If Left$(sText, Len(sStartWith)) <> sStartWith Then 'String doesn't start with specified text bPrepend = True End If End If If bPrepend Then 'Add the text StringStartWith = sStartWith & sText Else 'Return text unmodified StringStartWith = sText End If Else StringStartWith = sText End If End Function 'Purpose : Ensures the specified string always ends with a specific text. 'Inputs : sText The text to check the end characters of. ' sEndWith The text to ensure is a the end of sText parameter. ' [bIgnoreCase] If true performs a case insensitive comparison, else does not. 'Outputs : The specified string, ending with the sEndWith parameter. 'Author : Andrew Baker 'Date : 25/03/2005 'Notes : Public Function StringEndWith(ByRef sText, ByRef sEndWith As String, Optional bIgnoreCase As Boolean = True) As String Dim bPrepend As Boolean If Len(sEndWith) Then If bIgnoreCase Then If UCase$(Right$(sText, Len(sEndWith))) <> UCase$(sEndWith) Then 'String doesn't start with specified text bPrepend = True End If Else If Right$(sText, Len(sEndWith)) <> sEndWith Then 'String doesn't start with specified text bPrepend = True End If End If If bPrepend Then 'Add the text StringEndWith = sText & sEndWith Else 'Return text unmodified StringEndWith = sText End If Else StringEndWith = sText End If End Function 'Demo rountine Sub Test() Dim sPath As String sPath = "C:\Program Files\" 'First call will append the specified text sPath = StringEndWith(sPath, "My Path\") Debug.Print sPath 'Second call will do nothing sPath = StringEndWith(sPath, "My Path\") Debug.Print sPath End Sub
Terms and Conditions
Support this site
Download a trial version of the Excel Workbook Rebuilder