10

Is there an in-built numeric updown control in vba or do we need to create a control like that?

If there is such a control then what are the events that we may use.

Pls suggest.

Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
Premanshu
  • 616
  • 3
  • 14
  • 24

1 Answers1

23

You can use the SpinButton1 control for that

SNAPSHOT

enter image description here

CODE

You can either set the min and max of the SpinButton1 in design time or at runtime as shown below.

Private Sub UserForm_Initialize()
    SpinButton1.Min = 0
    SpinButton1.Max = 100
End Sub

Private Sub SpinButton1_Change()
    TextBox1.Text = SpinButton1.Value
End Sub

FOLLOWUP

If you want to increase or decrease the value of the textbox based on what user has input in the textbox then use this. This also makes the textbox a "Number Only" textbox which just fulfills your other request ;)

Private Sub SpinButton1_SpinDown()
    TextBox1.Text = Val(TextBox1.Text) - 1
End Sub

Private Sub SpinButton1_SpinUp()
    TextBox1.Text = Val(TextBox1.Text) + 1
End Sub

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    Select Case KeyAscii
      Case vbKey0 To vbKey9, 8
      Case Else
        KeyAscii = 0
        Beep
    End Select
End Sub
Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
  • Made my day.....In fact i linked two spin buttons with text boxes to achieve more means..... Is there a way to allow only numbers in a text box that has a spin control button linked with it....???? – Premanshu Jun 20 '12 at 10:48
  • Set the `.Locked` property of the Textbox to `TRUE` so that no user can manually type into it. Rest the spin buttons will take care of it :) – Siddharth Rout Jun 20 '12 at 10:54
  • Thanks Sid for all the help...that .locked things works fine.I'm allowing my users to manually enter the data...Though I have successfully restricted the entry of anything other than integers. ..but when I m entering the integers manually and then trying to increase/decrease it is not working fine. Say the value was 14 and now i manually change it to 5 and on click of increase it is becoming 15 instead of 6. Any ideas how to read this?? – Premanshu Jun 21 '12 at 06:41
  • 1
    Yes that is because it is taking the value of the spinner. Updating the post to incorporate your new request... 2 mins – Siddharth Rout Jun 21 '12 at 06:52
  • thanks man!!! may u pls suggest a better way to learn excel..i m trying by myself and using SO as one of the helping platforms.. – Premanshu Jun 21 '12 at 07:05
  • 1
    From a beginner's point of view I would recommend these `FREE` ways. `MSDN` + `Forums like SO` + `Google` :) When you have time, try and visit old questions and see how people have solved various problems. They are really a good way to learn :) If you want to buy a book, you might want to try a book by John Walkenbach. http://spreadsheetpage.com/index.php/books/ – Siddharth Rout Jun 21 '12 at 07:12