| Posted at 09:06 AM on December 29, 2008 |
When we write code that actually works (greatest feeling in the world) we most often want to make a decision or choice. Essentially, in human terms (or Martian, if there are any Martians reading this), we would say “when this happens then do this” or “if this had occurred, do that”. We wrote pretty much the same thing in our code from lesson 7, but like this:-
If intBoxOfApples = 8 Then
intBoxOfApples = 10
End If
But if we have more than one choice (goodness knows we nearly always do) then a good method to decide what to do is Select Case …. End Select. This command allows us to have several options (Cases, no suitcases – more like a legal or medical case) to choose from and carry out some code on one or several of these options. It works like this:-
Select Case intBoxOfApples
Case 4:
intBoxOfApples = 6
Case 8:
intBoxOfApples = 10
End Select
Replace the If….Then…End If code from the previous lesson with the Select Case code (above) and run it. If you can follow the logic, or flow, of the code you’ll see that when intBoxOfApples is equal to 4 (Case 4: ) the code will let intBoxOfApples equal 6, and again when it reaches 8 (Case 8: ) it will make intBoxOfApples equal to 10.
Try modifying with a few more results. You could even put in a few more MsgBox’s to test the results under each Case statement.
NOTE: # Programming is like lots of things in life, the more you do, the easier it is, until it becomes so easy its almost a no-brainer. Well I’ve almost no brains so everything must be easy, right?
Categories: VBA Tutorials (mixed nuts)