VBcoders Guest



Don't have an account yet? Register
 


Forgot Password?



ExtractArgument

by Brett Cramer (1 Submission)
Category: String Manipulation
Compatability: Visual Basic 3.0
Difficulty: Unknown Difficulty
Date Added: Wed 3rd February 2021
Rating: (4 Votes)

I use ExtractArgument (written by my friend Mike Carper) all the time. It returns an argument or token from a string based on its position within another string and a delimiter. For example: I want the "2" in the following string: "1,2,3,4,5,6,7,8,9,10".
'Sample call
'Dim sList as string
'Dim sTown as string
'sList = "POB 145,Dexter Street,Anytown,USA"
'sTown = ExtractArgument(3, sList, ",")
'sTown will be "Anytown"
I find this very useful in working with delimited files and strings, and have implemented it in INI settings as well.

Inputs
ArgNum As Integer srchstr As String Delim As String
Code Returns
The argument desired in a string format

Rate ExtractArgument

Function ExtractArgument (ArgNum As Integer, srchstr As String, Delim As String) As String
  'Extract an argument or token from a string based on its position
  'and a delimiter.
  On Error GoTo Err_ExtractArgument
  Dim ArgCount As Integer
  Dim LastPos As Integer
  Dim Pos As Integer
  Dim Arg As String
  
  Arg = ""
  LastPos = 1
  If ArgNum = 1 Then Arg = srchstr
  
   Do While InStr(srchstr, Delim) > 0
    Pos = InStr(LastPos, srchstr, Delim)
    If Pos = 0 Then
      'No More Args found
      If ArgCount = ArgNum - 1 Then Arg = Mid(srchstr, LastPos)
      Exit Do
    Else
      ArgCount = ArgCount + 1
      If ArgCount = ArgNum Then
        Arg = Mid(srchstr, LastPos, Pos - LastPos)
        Exit Do
      End If
    End If
    LastPos = Pos + 1
  Loop
  
  '---------
  ExtractArgument = Arg
  Exit Function
Err_ExtractArgument:
  MsgBox "Error " & Err & ": " & Error
  Resume Next
End Function

Download this snippet    Add to My Saved Code

ExtractArgument Comments

No comments have been posted about ExtractArgument. Why not be the first to post a comment about ExtractArgument.

Post your comment

Subject:
Message:
0/1000 characters