Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Split string into array

Status
Not open for further replies.
The split function will return an array of strings. This little code snippet will convert the array of strings to an array of longs. If the array is relatively small, execution time should be acceptable.

Code:
    Dim sTest As String
    Dim arLongs() As Long
    Dim arStrings() As String
    Dim i As Long
    
    sTest = "1,2,3,4,5,6"
    arStrings = Split(sTest, ",")
    
    ReDim arLongs(UBound(arStrings))
    
    For i = LBound(arStrings) To UBound(arStrings)
        arLongs(i) = CLng(arStrings(i))
    Next

Of course, there is no error handling here (making sure the elements of the original string can, in fact, be converted to a long.

Hope this helps.

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
I consider 50,000 elements to be relatively small. In fact, on my computer, it took less than 0.25 seconds to split the original string and iterate through it to convert it to a long.

I'm sure someone like strongm or hypetia will come along and present a better, faster way. Until then, give my method a try so that you can determine whether the perfomance will be fast enough for you.

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
Code:
    Dim i As Long
    Dim arTemp(50000) As String
    Dim sTest As String
    Dim arLongs() As Long
    Dim arStrings() As String
    Dim iTimer As Single
    
    For i = LBound(arTemp) To UBound(arTemp)
        arTemp(i) = Str(i)
    Next
    
    sTest = Join(arTemp, ",")
    Erase arTemp
    
    iTimer = Timer
    
    arStrings = Split(sTest, ",")
    
    ReDim arLongs(UBound(arStrings))
    
    For i = LBound(arStrings) To UBound(arStrings)
        arLongs(i) = CLng(arStrings(i))
    Next
    
    Erase arStrings
    Erase arLongs
    
    Call MsgBox("Time:  " & Round(Timer - iTimer, 4))

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top