Consulting

Results 1 to 4 of 4

Thread: Solved: vba ignore if statement in optiobutton

  1. #1

    Solved: vba ignore if statement in optiobutton

    hello,

    I have userform that works so far without errors except this one. When OptionButton5 is selected, then TextBox1 is enabled and the user has to type in a number between 1 and ArrayMax. Arraymax depends on the number of items in another sheet ( in my case it is 35).

    The code:

    [vba] ElseIf OptionButton5 Then
    TextBox1.Enabled = True
    ArrayMax = WorksheetFunction.Max(Worksheets("Vocabular Database").Range("A:A"))
    If TextBox1.Value = 0 Then
    MsgBox ("Minimim is 1")
    TextBox1.Value = vbNullString
    Exit Sub
    End If
    If TextBox1.Value > ArrayMax Then
    MsgBox ("Maximum is " & ArrayMax)
    TextBox1.Value = vbNullString
    Exit Sub
    End If
    ReDim myRandomArray(1 To TextBox1.Value)

    Else
    MsgBox ("You have to choose one option")
    Exit Sub[/vba]
    When I type in zero, it is working fine (MsgBox appear and then Exit sub), but any other number always prompt the MsgBox ("Maximum is " & ArrayMax), even VBA clearly knows that e.g. TextBox1.value is 8 and ArrayMax 35???

  2. #2
    Knowledge Base Approver VBAX Wizard p45cal's Avatar
    Joined
    Oct 2005
    Location
    Surrey UK
    Posts
    5,875
    Textbox1.value is a string, not a number. It needs to be converted/coerced to a number before comparing to ArrayMax. So some error required too, if the user puts in text which can't be converted to a number.
    p45cal
    Everyone: If I've helped and you can't be bothered to acknowledge it, I can't be bothered to look at further posts from you.

  3. #3
    VBAX Mentor
    Joined
    Feb 2009
    Posts
    493
    Location
    Try this

    [vba]ElseIf OptionButton5 Then
    TextBox1.Enabled = True
    ArrayMax = WorksheetFunction.Max(Worksheets("Vocabular Database").Range("A:A"))
    If CLng(TextBox1.Value) = 0 Then
    MsgBox ("Minimim is 1")
    TextBox1.Value = vbNullString
    Exit Sub
    End If
    If CLng(TextBox1.Value) > ArrayMax Then
    MsgBox ("Maximum is " & ArrayMax)
    TextBox1.Value = vbNullString
    Exit Sub
    End If
    ReDim myRandomArray(1 To TextBox1.Value)

    Else
    MsgBox ("You have to choose one option")
    Exit Sub
    [/vba]
    -----------------------------------------
    The more you learn about something the more you know you have much to learn.

  4. #4
    Yes that is working, thx!

Posting Permissions

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