I know in most other languages you can write an expression if (ptr == NULL || ptr->foo()) {something bad happened}
to test both the validity of a variable and a test you want to perform. VBA does not let you do that. So I am wracking my brain to figure out a way to write the following code without 1) using error catching as means of conditional branching and 2) not duplicating code.
Type Vector
vData() as Variant
vSize as Long
End Type
Sub add(v as Vector, elem as Variant)
Dim oldSize as Long
if v.vSize = 0 Or UBound(v.vData) >= v.vSize then
oldSize = v.vSize
ReDim Preserve v.vData(0 to (oldSize * 2 + 1))
v.vData(oldSize) = elem
v.vSize = v.vSize + 1
else
v.vData(v.vSize) = elem
v.vSize = v.vSize + 1
end if
End Sub
Now that code will crash on the UBound line regardless if vSize is 0 or not (if vData was never Dim'd). The only other way i can see to do it is do an additional elseif statement to check UBound, but that would duplicate the code of the doubling the vector size.
In case you think this is a duplicate: VBA Short-Circuit `And` Alternatives . This talks about alternatives to AND statements (not or). Nested ifs (aka AND statements) doesn't duplicate code like OR would.