title: VBA Excel - Textbox Validation
body: <p>So I'm trying to validate multiple textboxes. Here's the situation, some of my textboxes only accept <strong>numbers</strong> only while some accept <strong>letters with a dash</strong>. The codes below validate numbers only, but I don't know how can I combine them with the letters with a dash.</p>
  <p><a href="https://i.stack.imgur.com/XKuqN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XKuqN.jpg" alt="UserForm" /></a></p>
  <p>Class file:</p>
  <pre><code>Private WithEvents tb As MSForms.TextBox   'note the &quot;WithEvents&quot;
  
  Sub Init(tbox As Object)
      Set tb = tbox 'assigns the textbox to the &quot;tb&quot; global
  End Sub
  
  'Event handler works as in a form (you should get choices for &quot;tb&quot; in the
  '  drop-downs at the top of the class module)
  Private Sub tb_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
      If KeyAscii &gt;= 48 And KeyAscii &lt;= 57 Then
              Debug.Print tb.Name, &quot;number&quot;
              tb.MaxLength = 3
      Else
          MsgBox &quot;The value should be in number only!&quot;, vbOKOnly + vbCritical, &quot;Error&quot;
          Debug.Print tb.Name, &quot;other&quot;
          KeyAscii = 0
      End If
      
  End Sub
  </code></pre>
  <p>Userform file:</p>
  <pre><code>Private colTB As Collectione
  
  Private Sub UserForm_Activate()
      Dim c As Object
      Set colTB = New Collection
      'loop all controls in the frame
      For Each c In Me.Frame3.Controls
          'look for text boxes
          If TypeName(c) = &quot;TextBox&quot; Then
              Debug.Print &quot;setting up &quot; &amp; c.Name
              colTB.Add TbHandler(c) ' create and store an instance of your class
          End If
      Next c
  End Sub
  
  Private Function TbHandler(tb As Object) As clsTxt
      Dim o As New clsTxt
      o.Init tb
      Set TbHandler = o
  End Function
  </code></pre>
  <p>Validation for letters with a dash:</p>
  <pre><code>If (KeyAscii &lt; 65 Or KeyAscii &gt; 90) And (KeyAscii &lt; 97 Or KeyAscii &gt; 122) And KeyAscii &lt;&gt; 45 Then
              MsgBox &quot;The value should be in letters only!&quot;, vbOKOnly + vbCritical, &quot;Error&quot;
              Debug.Print tb.Name, &quot;other&quot;
              KeyAscii = 0
      Else
          Debug.Print tb.Name, &quot;letter&quot;
  End If
  </code></pre>