validating text boxes in user forms

VBAmalta89

Board Regular
Joined
Mar 25, 2011
Messages
116
I have a user form which contains a frame with 20 text boxes. Is there a way to create a validation procedure to ensure that only numbers are entered in the text boxes?

Ideally a code which can be used for all text boxes within the frame would be available. Currently I am trying to do it by validating each and every text box but it comes very long as I need to repeat the process 20 times!
 

Excel Facts

Return population for a City
If you have a list of cities in A2:A100, use Data, Geography. Then =A2.Population and copy down.
Hi,

More specifically, try this:

Create a Class module named TBClass containing this code:
Code:
Option Explicit

'   Class module named TBClass

Public WithEvents TBGroup As MSForms.TextBox

Private Sub TBGroup_Change()
Dim iPtr As Integer
Dim sValueIn As String, sValueOut As String, sChar As String

sValueIn = TBGroup.Value
If IsNumeric(sValueIn) = False Then
    For iPtr = 1 To Len(sValueIn)
        sChar = Mid$(sValueIn, iPtr, 1)
        If IsNumeric(sChar) Then sValueOut = sValueOut & sChar
    Next iPtr
With Application
    .EnableEvents = False
    TBGroup.Value = sValueOut
    .EnableEvents = True
End With

End If
End Sub

Add this code to your userform:
Code:
Option Explicit

'Userform Code

Dim TBs() As New TBClass

Private Sub UserForm_Initialize()
    Dim TBCount As Integer
    Dim Ctrl As Control
    TBCount = 0
    For Each Ctrl In UserForm1.Controls
        If TypeName(Ctrl) = "TextBox" Then
            TBCount = TBCount + 1
            ReDim Preserve TBs(1 To TBCount)
            Set TBs(TBCount).TBGroup = Ctrl
        End If
    Next Ctrl
End Sub
 
Upvote 0

Forum statistics

Threads
1,224,522
Messages
6,179,297
Members
452,903
Latest member
Knuddeluff

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top