views:

162

answers:

1

In the standard IDE for VBA, intellisense is built-in to many standard VBA functions. i.e. the buttons variable for msgbox() gives you a list of options for how you want the messagebox to be displayed. This way, the developer doesn't have to memorize or look up the options every time function is used.

Can I achieve the same for my custom VBA functions? This is a rough example, but can i write something like:

Public Function DoSomething(X as string)(Options X="Opt1","Opt2") as variant
...

When I call this function, I would get a pop-up giving my options for X as Opt1 and Opt2

+3  A: 

You'll need to declare your own enumerations, and then define the parameter to your functions as that enumerated type.

Public Enum eOptions
   Option1
   Option2
End Enum

public Function DoSomething(ByVal x as string, Byval MyOption as eOptions)

When you call the function ala this:

Call DoSomething("myValue", Option2)

You'll see the values available for the second parameter to the function as either "Option1" or "Option2".

Tim Lentine
+1 But using "option" as a parameter name confused Access 2003. Option is a keyword.
HansUp
@HansUp Thanks for catching that one. I edited the answer by re-naming the second parameter.
Tim Lentine
Good answer. A further question: How do I convert from the number constant back to the string constant? i.e. Using the example above, is there a CEnum(0) which would return "Option1"?
PowerUser
I don't believe there is, but others might know of a way. One "hack" I've seen when you *must* get the string value out of the enum is to use a lookup table which contains the enum value (0,1,2) and the associated string value. This gets messy quickly though, so I wouldn't advise going down this road. Use enums in your code when you need to restrict yourself or others to a known set of values and work with those values in your code rather than the string representation.
Tim Lentine
This to me is one of the annoying things about Enums as implemented in VBA -- they are of no use except to the programmer, since you can't actually ENUMERATE through them in code. I went through a period when I got all excited about the, and then decide they were pretty much useless, and decide it was a bad idea to store data in code.
David-W-Fenton
I completely agree. There are a few cases where they make your code more readable, but for the most part they aren't worth the hassle.
Tim Lentine

related questions