VBA code with comments that generates a random number between 1 and 100 and displays a message box indicating whether the number is even or odd


 Sub RandomNumber()

    'Declare variables

    Dim num As Integer

    Dim result As String

    

    'Generate random number between 1 and 100

    Randomize

    num = Int((100 * Rnd) + 1)

    

    'Check if number is even or odd

    If num Mod 2 = 0 Then

        result = "even"

    Else

        result = "odd"

    End If

    

    'Display message box with result

    MsgBox "The random number is " & num & ", which is " & result & "."

End Sub



This code uses the Randomize function to generate a random number between 1 and 100, then checks whether the number is even or odd using the Mod operator. Finally, it displays a message box with the result.

You can run this code by opening the Visual Basic Editor, inserting a new module, and pasting the code. Then, run the RandomNumber subroutine by clicking on it and pressing F5 or by going to Run > Run Sub/UserForm in the VBE menu.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.