'Do not allow decimal numbers in UserForm TextBox - VBA

How to check for only Whole numbers ? no decimals allowed.

'Below is the code to check for numbers
For j = 1 To 59
    If Me.Controls("TextBox" & j).Value = "" Then
    Else
        If Not IsNumeric(Me.Controls("TextBox" & j).Value) Then
        MsgBox "only numbers are allowed"
        Cancel = False
        Exit Sub
        End If
    End If
Next j


Solution 1:[1]

I think it is a better user experience to check as the user types not after the fact. Try something like this:

Option Explicit

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
   If Not GoodKeyPress(KeyAscii) Then KeyAscii = 0
End Sub

Private Sub TextBox2_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
   If Not GoodKeyPress(KeyAscii) Then KeyAscii = 0
End Sub

Private Function GoodKeyPress(ByVal KeyAscii As MSForms.ReturnInteger) As Boolean
   If KeyAscii = 46 Then MsgBox "No decimal allowed"

   'allow only numbers, negative sign and backspace
   If (KeyAscii >= 48 And KeyAscii <= 57) Or KeyAscii = 45 Or KeyAscii = 8 Then GoodKeyPress = True
End Function

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1