这是上一个关于 Excel UseForm 中文本框特定验证的问题的延续。Sorceri在获取此代码方面帮助了我很多,但我现在需要一些微调。我需要在不同的文本框中进行不同的验证。我已经通过“工具箱”中的“控件”构建了文本框。他们按顺序命名;“info1”、“info2”、“info3”等等。
大多数文本框的验证如下所示(“1-5”、“88”和“99”)。但是,其中两个文本框需要进行不同的验证(“1-3”和“88”)。除此之外,还需要为第三组文本框(“0-10”和“88”)设置第三个验证集。总的来说,我对 VBA 和编程还很陌生,但我学得很快。任何帮助将不胜感激。
为了澄清,我在 Sorceri 旁边的括号中添加了我自己的评论。再次感谢大家。
Private Sub cmdEnter_Click()
Dim ctl As Control
For Each ctl In Me.Controls
'check to see if it is a textbox (I'm guessing I could specify which textboxes here, but I'm unsure)
If TypeOf ctl Is MSForms.TextBox Then
Dim tBox As MSForms.TextBox
Set tBox = ctl
'we have a textbox so validate the entry (Again, I'm hoping to make this into, "We found textbox variant A and so will validate its entry with validation A, etc)
If validateTextBox(tBox) Then
'did not validate so set focus on the control
MsgBox "Invalid Entry!", vbCritical, "Invalid!"
ctl.SetFocus
'release the object
Set tBox = Nothing
Exit Sub
End If
Set tBox = Nothing
End If
Next
End Sub
'validate a textbox's value and return true or false
Private Function validateTextBox(tb As MSForms.TextBox) As Boolean
Dim sValue As String
Dim bInvalid As Boolean
bInvalid = True
sValue = Trim(tb.Text)
If sValue = "1" Or sValue = "2" Or sValue = "3" Or sValue = "4" Or sValue = "5" Or sValue = "99" Or sValue = "88" Then
bInvalid = False
End If
'return the results
validateTextBox = bInvalid
End Function