简体   繁体   中英

How do I split the string into a long() type array in Excel VBA?

Let's say I have something like "1-34-52" , I want to split them into an array, however, while Test1 works, it gives me an String() type array. How do I put the numbers in "1-34-52" into a Long() type array? Can I redim type of an array in VBA?

Sub Test1()
    Dim arr As Variant
    arr = Split("1-34-52", "-")
    Debug.Print TypeName(arr), TypeName(arr(0))
End Sub

Sub Test2()
    Dim arr() As Long
    arr = Split("1-34-52") 'You get type mismatch error
End Sub

You can Redim an array of Variants . Since Variants can hold integer values, there is no problem:

Sub dural()
    ary = Split("1-34-52", "-")
    ReDim lary(0 To UBound(ary))
    For i = 0 To UBound(ary)
        lary(i) = CLng(ary(i))
    Next i
End Sub

Note:

Sub dural()
    ary = Split("1-34-52", "-")
    Dim lary() As Long
    ReDim lary(0 To UBound(ary))
    For i = 0 To UBound(ary)
        lary(i) = CLng(ary(i))
    Next i
End Sub

will also work.

You can loop through the array and populate a new one:

Sub Test1()
    Dim arr As Variant, LongArr() As Long, X As Long
    arr = Split("1-34-52", "-")
    ReDim LongArr(UBound(arr))
    For X = LBound(arr) To UBound(arr)
        LongArr(X) = CLng(arr(X))
    Next
    Debug.Print TypeName(arr), TypeName(arr(0))
    Debug.Print TypeName(LongArr), TypeName(LongArr(0))
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM