Bob Vesterman
Bob Vesterman

Reputation: 1211

How do I make a VB6 variant array with UBound < LBound?

I'm trying to get rid of dependencies on SCRRUN.DLL in a VB6 application. One of the things it's currently being used for is its Dictionary class. The Dictionary class has a Keys function that is supposed to return an array of the keys in the dictionary. I did a little experimentation to see what happens if there are no keys in the dictionary:

Dim D As Dictionary
Set D = New Dictionary
Dim K() As Variant
K = D.Keys
MsgBox LBound(K) & ", " & UBound(K)

I was expecting "subscript out of range", or something similar, but instead I was informed that the LBound is 0 and the UBound is -1.

So, how can I create a Variant array that has LBound 0 and UBound -1?

I've tried just using an uninitialized variant array:

Dim K() as Variant
MsgBox LBound(K) & ", " & UBound(K)

But of course that throws "Subscript out of range", as I would expect. So does erasing an uninitialized array:

Dim K() as Variant
Erase K
MsgBox LBound(K) & ", " & UBound(K)

As does erasing an initialized array:

Dim K() As Variant
ReDim K(0 To 0)
Erase K
MsgBox LBound(K) & ", " & UBound(K)

I also tried just redimming to 0 and -1, strange as that may seem:

Dim K() As Variant
ReDim K(0 To -1)
MsgBox LBound(K) & ", " & UBound(K)

But that also gives "subscript out of range".

Poking around on the web a bit, I found the following trick:

Dim K() As String
K = Split(vbNullString)
MsgBox LBound(K) & ", " & UBound(K)

And that actually does give an array with LBound 0 and UBound -1! Unforunately, it's a String array, whereas I need a Variant array. I can't very well individually copy the Strings from one array to Variants in another array, because, well, 0 to -1 and all.

Does anyone know how to make such an array, Variant() with LBound 0 and UBound -1, without using SCRRUN.DLL? Preferably also using only built-in VB6 stuff, but if you can do it if you're allowed to use some external thing (other than SCRRUN.DLL), I'm all ears. Thanks.

Upvotes: 2

Views: 3717

Answers (2)

Holistic Developer
Holistic Developer

Reputation: 2526

You can use the Array function:

Dim K()
K = Array()
MsgBox UBound(K)

Upvotes: 5

Bob Vesterman
Bob Vesterman

Reputation: 1211

OK, answering my own question (but using OLEAUT32.DLL; I'd still be interested in any solutions that are pure built-in VB6):

Private Declare Function SafeArrayCreateVector Lib "OLEAUT32.DLL" ( _
    ByVal vt As VbVarType, ByVal lLbound As Long, ByVal cElements As Long) _
    As Variant()

Private Const VT_VARIANT As Long = 12

(...)

Dim K() As Variant
K = SafeArrayCreateVector(VT_VARIANT, 0, 0)
MsgBox LBound(K) & ", " & UBound(K)

Upvotes: 1

Related Questions