Listing A Procedure That Uses Select Case to Convert a Raw Test Score into a Letter Grade

Function LetterGrade(rawScore As Integer) As String Select Case rawScore Case Is < 0

LetterGrade = "ERROR! Score less than 0!" Case Is < 60

LetterGrade = "C"

LetterGrade = "A" Case Else

LetterGrade = "ERROR! Score greater than 100!"

End Select End Function

The rawScore argument is an integer value between 0 and 100. The Select Case structure first checks to see whether rawScore is negative and, if so, the function returns an error message. The next Case statement checks to see whether the score is less than 60, and the function returns the letter grade "F" if it is. The next Case statement looks for a score that is less than 70. If we get this far, we already know (thanks to the preceding Case statement) that the score is at least 60. Therefore, this case is really checking to see whether the score is between 60 and 70 (including 60, but not including 70). If so, the letter grade "D" is returned. The rest of the Case statements proceed in the same manner. The Case Else checks for a score greater than 100 and returns another error message if it is.

Another Example: Taming the RGB Function

In Chapter 5, "Working with Objects," I mentioned briefly that you can use the RGB (red,green,blue) VBA function anytime you need to specify a color for a property. Each of the three named arguments (red, green, and blue) are integers between 0 and 255 that determine how much of each component color is mixed into the final color. In the red component, for example, 0 means no red is present and 255 means that pure red is present. If all three values are the same, you get a shade of gray.

Here are some sample values for each component that produce common colors:

Red

Green

Blue

Result

0

0

0

Black

0

0

255

Blue

0

255

0

Green

0

255

255

Cyan

255

0

0

Red

255

0

255

Magenta

255

255

0

Yellow

255

255

255

White

However, rather than memorize these combinations, let's put VBA and Select Case to work to make choosing colors easier. Listing 6.7 shows the VBAColor function, which lets you use names (for example, "red" or "blue") rather than cryptic number combinations to set 16 of the most common colors.

0 0

Post a comment