Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variant but not an Object

Tags:

excel

vba

variant

If I know a bit of data is going to be an Object, but I don't know what kind, I can pass it to a function or routine like this:

Sub mySubExpectingAnObject(myVal As Object)

Which is more explicit than

Sub mySubExpectingAnObject(myVal As Variant)

And should be preferred even if both work

If instead I know the bit of data is not an object, but could be anything else (Long, Double, String etc.), is there any way of Diming the argument as not an object. E.g

Sub mySubExpectingNotAnObject(myVal As NotObject)

Since if I use Variant here, there will be no automatic anti-object check. Does such a type exist; one that can encapsulate any non-object datatype exclusively? Is there a workaround other than just

If isObject(myVal) Then Err.Raise 5

or similar?

like image 802
Greedo Avatar asked Mar 06 '23 03:03

Greedo


1 Answers

I don't see what's wrong with using a Variant and throwing an invalid procedure call or argument run-time error 5, which pretty much literally says "this procedure was invoked with an invalid argument", given IsObject(theParameter) returning True.

Variant exists specifically to lift the compile-time type constraints so that VBA can deal with foreign types such as IUnknown and whatnot: there's no way you can use a Variant and enforce any kind of compile-time check against it - by definition a Variant's type is only resolved at run-time.

The idiomatic way to solve this, is to use good, meaningful names for both your procedure and their parameters. Pretty hard to recommend anything with the examples you've got though.

There is no "variant but not an object" type, and you can't use a Variant and expect any kind of type validation at compile-time.

like image 80
Mathieu Guindon Avatar answered Mar 08 '23 17:03

Mathieu Guindon