VB and VBA Users Source Code: Returning a field from a delimited string (eg a connection string)
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
VB/VBA Source Code
Returning a field from a delimited string (eg a connection string)
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Tuesday, August 14, 2001
Hits:
646
Category:
Visual Basic General
Article:
The following routine is useful when retrieving sections from within a string eg. when trying to split a command line into parameters/arguments. 'Purpose : Parses a deliminated string for key/value pair and returns the value. 'Inputs : sValue The string to return the item value from. ' sStartDelim The delimeter which denotes the start of the string ' [sEndDelim] The delimeter which denotes the end of the string. ' If not specified uses the end of the string. ' [sDefault] The default value to return if the item is not found ' [bTrimText] If True trims the resulting string. 'Outputs : Returns the requested portion of the string (without the delimeters). 'Author : Andrew Baker 'Date : 06/07/2001 'Notes : If it doesn't find the sEndDelim, will use the end of the string ' eg. ' StringParse("DB=TEST_DB;USER=ANDREW","USER=",";") ' Returns "ANDREW" ' Design primarily for use with command line arguments 'Revisions : Function StringParse(sValue As String, sStartDelim As String, sEndDelim As String, Optional sDefault As String = "", Optional bTrimText As Boolean = True) Dim lPosStart As Long, lPosEnd As Long, lLen As Long Dim lLenStartDelim As Long, lLenEndDelim As Long On Error GoTo ErrFailed 'Determine string properties lLen = Len(sValue) lLenStartDelim = Len(sStartDelim) lLenEndDelim = Len(sEndDelim) 'Find start delimeter lPosStart = InStr(1, sValue, sStartDelim, vbTextCompare) If lPosStart Then lPosStart = lPosStart + lLenStartDelim 'Find end delimeter If Len(sEndDelim) Then lPosEnd = InStr(lPosStart, sValue, sEndDelim, vbTextCompare) End If If lPosEnd = 0 Then 'Did not find end delimeter, use the end of the string lPosEnd = lLen + 1 End If 'Return resulting string StringParse = Mid$(sValue, lPosStart, lPosEnd - lPosStart) If bTrimText Then 'Trim leading and trailing spaces StringParse = Trim$(StringParse) End If Else 'Did not find item StringParse = sDefault End If Exit Function ErrFailed: Debug.Assert False Debug.Print "StringParse Error: " & Err.Description On Error GoTo 0 End Function
Terms and Conditions
Support this site
Download a trial version of the Excel Workbook Rebuilder