Visual Basic 6 function "SplitCommandLine"

Go back

Below you'll find the source for the Visual Basic 6 function SplitCommandLine.

Attribute VB_Name = "modSplitCommandLine"
' This function is downloaded from:
' http://www.stefanthoolen.nl/archive/vb6-functions/
' 
' You may freely distribute this file but please leave all comments, including this one, in it.
' 
' @Author Stefan Thoolen <mail@stefanthoolen.nl>

Option Explicit

''
' Splits a string into multiple parts as if it is a command line
' If you don't specify txt, command$ will be used instead
' Example:
'    Dim s() As String
'    SplitCommandLine s, "a b c   d ""e f g"" h"
'    MsgBox Join(s, ",")
' @param    Array   ret         The returned value
' @param    String  txt         Optional, the string that must be parted. If not specified, command$ will be used
' @return   Void
' @author   Stefan Thoolen <mail@stefanthoolen.nl>
Public Sub SplitCommandLine(ByRef ret() As String, Optional ByVal txt As String)
    If txt = "" Then txt = Command$
    txt = txt & " " ' Causes the last value to be parsed as well :-)
    
    Dim i As Integer, s As String, cnt As Integer
    Dim in_quotes As Boolean, tmp As String
    For i = 1 To Len(txt)
        s = Mid(txt, i, 1)
        ' Checks if we are in quotes or not
        If s = Chr(34) Then in_quotes = Not in_quotes
        ' Yay, whitespace :-)
        If s = " " And Not in_quotes Then
            tmp = Trim(tmp)
            If tmp <> "" Then
                ReDim Preserve ret(0 To cnt)
                ' Removes quotes, if needed
                If Left(tmp, 1) = Chr(34) And Right(tmp, 1) = Chr(34) Then tmp = Mid(tmp, 2, Len(tmp) - 2)
                ret(cnt) = tmp
                ' Next!
                cnt = cnt + 1: tmp = ""
            End If
        End If
        tmp = tmp & s
    Next i
End Sub