+ Reply to Thread
Results 1 to 2 of 2

excel nested if statement

  1. #1
    Registered User
    Join Date
    03-26-2009
    Location
    canada
    MS-Off Ver
    Excel 2003
    Posts
    1

    excel nested if statement

    I am new to excel vba... The code is below is using the nested if statement to display the two random number based on the user input say one or two. I am getting a compile error where the else statement is. The first if statement works but cannot get the second one to work...any ideas?

    Help is appreciated

    here is the code:

    Dim Random1 As Integer, Random2 As Integer, Random3 As Integer 'declare varible for random number
    Dim Random

    Randomize ' generate new random number

    'Generating random number 1
    For i = 10 To 100
    Random1 = Int((100 - 10 + 1) * Rnd + 10)
    Next i

    'generating random number 2
    For i = 10 To 100
    Random2 = Int((100 - 10 + 1) * Rnd + 10)
    Next i

    'Input box which allows the user to input a number
    Random = Val(InputBox("Enter the Random Number(1 or 2) you would like to select: ", "Random Number"))


    'If Random < 1 Or Random > 2 Then

    'MsgBox ("Random Number must be 1 or 2")

    'End If

    If Random = 1 Then

    If Random1 > Random2 Then
    MsgBox ("win")

    ElseIf Random1 < Random2 Then
    MsgBox ("lose")

    End If
    End If


    Else
    If Random = 2 Then
    If Random2 > Random1 Then
    MsgBox ("win")

    ElseIf Random2 < Random1 Then
    MsgBox ("lose")

    End If
    End If


    'the message will display the random number generated for number 1 and number 2 plus the Random Number selected
    'either 1 or 2 to determine if we win or lose.

    MsgBox ("Random number 1 is " & Random1 & " and Random number 2 is " & Random2 & " and you selected random number " & Random)



    End Sub

  2. #2
    Forum Moderator - RIP Richard Buttrey's Avatar
    Join Date
    01-14-2008
    Location
    Stockton Heath, Cheshire, UK
    MS-Off Ver
    Office 365, Excel for Windows 2010 & Excel for Mac
    Posts
    29,464

    Re: excel nested if statement

    Hi, and welcome to the forum.
    Please take a moment to review the forum rules which require VBA code to be wrapped between code tags. This makes it far easier to read. Since this is your first post, please make a note.

    As to your problem, it looks like the Else statement is outside an IF..End IF statement.

    HTH
    Richard Buttrey

    RIP - d. 06/10/2022

    If any of the responses have helped then please consider rating them by clicking the small star icon below the post.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1