Simple If/Then/else Question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • imd321
    New Member
    • Jun 2008
    • 1

    #1

    Simple If/Then/else Question

    I'm trying to do a very simple if, then, else program in excel VBA (which I'ved simplified even further below). What I'm hoping will happen is that it will keep asking me for a variable until its greater than 5 and then it will post a single message of 'finished'
    What actually happens is that depending on how many time I provide an input before I get to something that's greater than 5 it will then repeat the 'finished' message that number of times. What am I doing wrong.

    Sub test()
    Dim var1 As Variant

    var1 = InputBox("varia ble please")
    If var1 < 5 Then
    Call test
    Else
    MsgBox ("two")
    End If

    MsgBox ("finished")
    End Sub
  • kadghar
    Recognized Expert Top Contributor
    • Apr 2007
    • 1302

    #2
    Thats because the msgbox is shown once for everytime you call Test, because it always run up to the last line.

    Imagine you enter the number > 5 in the 2nd attemp. then the first atemp will call Test again, in the second one, Test will finish and show "Finished", then it'll go back to finish the Test you started first, and i'll do so

    Msgbox("two") will show only once ^.^
    that'll give you an idea.

    what i recomend you to do here is not to use a recursion formula. A single loop is enough:

    [CODE=vb]sub test()
    dim var1
    do
    var1=inputbox(" variable please")
    loop until var1 > 5
    msgbox "two"
    msgbox "finish"
    end sub[/CODE]
    HTH

    Comment

    Working...