04/28/2001 - Describes the usage of the Choose() function; A really neat but seldom used command in VB.
Submitted On | |
By | Matthew Roberts |
Level | Beginner |
User Rating | 4.5 (27 globes from 6 users) |
Compatibility | VB 3.0, VB 4.0 (16-bit), VB 4.0 (32-bit), VB 5.0, VB 6.0, VB Script, ASP (Active Server Pages) , VBA MS Access, VBA MS Excel |
Category | Coding Standards |
World | Visual Basic |
Archive File |
The Daily Newbie
“To Start Things Off Right”
Fourth Edition April 28, 2001 Free
About this feature:
The initial plan for the Daily Newbie was to cover each function VB has to offer in alphabetical order. I have now modified this plan slightly to skip over some of the more advanced (or tedious) commands that I don't think the Newbie would benefit from. Thanks again all who have written in support of this effort. It makes a difference.
Today's command is not widely known for some reason, but is faily useful. I have been guilty of writing functions that do the exact same thing several times. I think you will like this one.
Today’s Keyword: Choose()
Name Derived From:
Choose (of course) – “(1) : to make a selection" - Webster's online dictionary.
Used for Making a choice between several possible options.
VB Help Description: Selects and returns a value from a list ofarguments.
Plain English: Returns the option associated with the value passed it (I will just have to show you!)
Syntax: Choose(index, Choice1, Choice2, etc...)
Usage: strDecision = Choose(intChoice , "Just do it" , "Don't do it" , "It's your life" )
Copy & Paste Code:
Today's code snippet will prompt for a month number and return a string that corresponds to it.
Dim Choice Dim strMonth As String Do Choice = Val(InputBox("Enter a Number (1-12):")) If Choice + 0 = 0 Then Exit Do strMonth = Choose(Choice, "Jan", "Feb", "Mar", "Apr", _ "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") MsgBox strMonth Loop
Notes:
I really like the Choose function. It comes in handy for with evaluating which option button was clicked, or anything else that returns an index number. Unfortunatly, like the Array() command covered a couple of articles ago, the Choose() function requires a seperate hard coded value for each possible choice. This isn't neccesarily a bad thing, but I am allergic to hard coding, so it just rubs me wrong. I guess the chances of the order of the months changing is pretty slim...Things to watch out for:
Tomorrow's Keyword: Chr()