Search code examples
arraysvb6upperbound

vb6 array with -1 for upper bound


Some functions such as Split() will return an array with -1 for the upper bound and zero for the lower bound if the array has no items, eg:

Dim s() As String
s = Split("", ",")
Debug.Print UBound(s)
Debug.Pring LBound(s)

In this case UBound(s) will equal -1 and LBound(s) will equal 0. I have a fair amount of code checking for -1 on the upper bound to see if the array has values or not. This works great.

The problem is that I now want to change the array data type from string to long. I cannot seem to create an array of longs with an upper bound of -1 and a lower bound of 0, and the Split() and Join() functions only operate on string arrays.

I would like to be able to return a long array with an upper bound of -1. Is this possible?


Solution

  • I don't think you can do it in VB6 it self. However, if you're willing to use the Windows API function SafeArrayCreateVector you can do it:

    Private Declare Function LongSplitEmulator Lib "OLEAUT32.DLL" Alias "SafeArrayCreateVector" _
        (Optional ByVal vt As VbVarType = vbLong, _
         Optional ByVal low As Long = 0, _
         Optional ByVal count As Long = 0) As Long()
    
    Dim a() As Long
    a = LongSplitEmulator()
    MsgBox UBound(a)
    

    If you need to do it for other datatypes you can change the vt parameter.

    Please note, I think I originally found out about this from Vi2's answer to this discussion.