Here’s another handy bit from my VB6 code shed out back.
If you’ve worked much with databases in VB6, you know that you almost always end up having to deal with database NULLs at some point.
And, in VB6, the only variable type that can actually deal with nulls is the Variant.
For the most part, my code avoids nulls by coercing them to the most appropriate “null value”, either a 0, or a 0 length string, etc, depending on the underlying data type.
However, there are instances where I’ve needed to compare two values directly from the database, and didn’t want to coerce them up front.
That’s where this handy routine comes in.
Public Function CompareVariant(Var1 As Variant, Var2 As Variant, Optional CompareMethod As VbCompareMethod = vbBinaryCompare) As Long '---- Compare 2 variants that might contain NULL or empty values Dim bVal1Null As Boolean Dim bVal2Null As Boolean Dim bVal1Empty As Boolean Dim bVal2Empty As Boolean Dim bSameValues As Boolean bVal1Null = IsNull(Var1) bVal1Empty = IsEmpty(Var1) bVal2Null = IsNull(Var2) bVal2Empty = IsEmpty(Var2) '---- variants are the same if ' 1) both are null ' 2) both are empty ' 3) they are otherwise equal If (bVal1Null And bVal2Null) _ Or (bVal1Empty And bVal2Empty) Then CompareVariant = 0 Else '---- you can only check for equal values is if neither of the values is Null or Empty If Not (bVal1Null Or bVal1Empty Or bVal2Null Or bVal2Empty) Then If CompareMethod = vbTextCompare Then CompareVariant = StrComp(CStr(Var1), CStr(Var2), vbTextCompare) Else If Var1 > Var2 Then CompareVariant = 1 Else CompareVariant = (Var1 < Var2) End If End If ElseIf bVal1Null Then '---- This is arbitrary, I'm determining that NULL is < empty ' this might not be universally appropriate, though CompareVariant = -1 Else CompareVariant = 1 End If End If End Function
Basically, the idea is similar to the built-in VB function StrComp, but it intelligently deals with potentially NULL or empty variants as well.
Are there faster ways to do this? Probably. But I find I need the functionality so infrequently, it hasn’t been a priority to optimize.
Still, if you need it, coding this up each time would be a complete pain in the ass (and unfortunately, I’ve seen that tack taken more than a few times).
If anyone can improve on this, please let me know!