BUY EXCEL BOOKS ONLINE: 1. VBA & Macros      2. VBA for Modelers      3. Excel 2013 VBA and Macros     
4. Excel VBA for Dummies      5. Excel with VBA & .NET      6. Mastering VBA      7. Excel 2013 Programming

Use of Random Function (Rnd) and Select Case statement


Brief Description:
Here, I present the code to use random function in association with the Select Case statement. It use random function to generate a random value of S, H, D, or C for the four card suits (spades hearts diamonds or clubs). When user clicks the button, an input box pops up to accepts a value of S, H, D, C If the guess matches the random number respond with “Good guess”, if not then it respond with “Bad Guess”.

Code:
Sub GuessNumbers()
    Dim myStr As String
    myStr = InputBox("Please enter ""S"", ""H"",""D"" or ""C""", "Make a Guess", "")
    Select Case Rnd(1) * 10 Mod 4
    Case 0
        Select Case UCase(myStr)
            Case "S"
                MsgBox "Good Guess"
            Case "H"
                MsgBox "Bad Guess"
            Case "D"
                MsgBox "Bad Guess"
            Case "C"
                MsgBox "Bad Guess"
        End Select
    Case 1
        Select Case UCase(myStr)
            Case "S"
                MsgBox "Bad Guess"
            Case "H"
                MsgBox "Good Guess"
            Case "D"
                MsgBox "Bad Guess"
            Case "C"
                MsgBox "Bad Guess"
        End Select
    Case 2
        Select Case UCase(myStr)
            Case "S"
                MsgBox "Bad Guess"
            Case "H"
                MsgBox "Bad Guess"
            Case "D"
                MsgBox "Good Guess"
            Case "C"
                MsgBox "Bad Guess"
        End Select
    Case 3
        Select Case UCase(myStr)
            Case "S"
                MsgBox "Bad Guess"
            Case "H"
                MsgBox "Bad Guess"
            Case "D"
                MsgBox "Bad Guess"
            Case "C"
                MsgBox "Good Guess"
        End Select
    End Select
End Sub