Validation 正在验证userform文本框条目的格式

Validation 正在验证userform文本框条目的格式,validation,excel,textbox,userform,vba,Validation,Excel,Textbox,Userform,Vba,我有一个数据库数据提取器的用户表单。其中有一个文本框,用于输入用户要提取数据的零件号。我想验证在提取程序运行之前,用户是否输入了正确的零件号格式。为此,我需要一个代码来验证文本是否以特定格式输入: 3个数字字符 1个字母字符或1个连字符 然后是5个数字字符 我首先尝试了以下验证: 'validate that box is not empty If TextBox1.Value = "" Then MsgBox ("Sorry, you need to provide an Amount

我有一个数据库数据提取器的用户表单。其中有一个文本框,用于输入用户要提取数据的零件号。我想验证在提取程序运行之前,用户是否输入了正确的零件号格式。为此,我需要一个代码来验证文本是否以特定格式输入:

3个数字字符 1个字母字符或1个连字符 然后是5个数字字符

我首先尝试了以下验证:

'validate that box is not empty 

If TextBox1.Value = "" Then 

MsgBox ("Sorry, you need to provide an Amount") 

TextBox1.SetFocus 

Exit Sub 

End If 


'validate that box is numeric 

If Not IsNumeric(TextBox1.Value) Then 

MsgBox ("Sorry, must enter a numer") 

TextBox1.SetFocus 

Exit Sub 

End If 
但后来我意识到我有个问题,第四个位置可能有字母字符或连字符

如果有任何建议,我将不胜感激


提前感谢。

检查此输入的初学者方法是切碎输入字符串并根据需要比较各个部分:

Const alpha as String = "abcdefghijklmnopqrstuvwxyz-"
Dim strValue as String
Dim msg as String
strValue = TextBox1.Value

'Make sure it's the right LENGTH
If Len(strValue) <> 9 Then 
    msg = "Please enter the ID as 3 numeric, 1 alpha/hyphen, 5 numeric"
    GoTo EarlyExit
End If

'Check the first three for numeric:
If Not IsNumeric(Left(strValue), 3) Then
    msg = "The first three characters should be numeric"
    GoTo EarlyExit
End If

'Check the middle character, assuming case not sensitive:
If Instr(1, alpha, Lcase(Mid(strValue, 4, 1)) = 0 Then 
    msg = "The fourth character should be hyphen or alphabet"
    GoTo EarlyExit
End If

'Check the last four characters
If Not IsNumeric(Right(strValue, 4)) Then
    msg = "The last four characters should be numeric"
    GoTo EarlyExit
End If

'If you've gotten here, then the input is validated:
Exit Sub 

EarlyExit:
MsgBox msg
TextBox1.SetFocus
End Sub
常量alpha as String=“abcdefghijklmnopqrstuvxyz- 作为字符串的Dim strValue 作为字符串的Dim msg strValue=TextBox1.Value “确保长度合适 如果Len(strValue)9那么 msg=“请将ID输入为3个数字、1个字母/连字符、5个数字” 去早退 如果结束 '检查前三个数字: 如果不是数字(左(右值),3),则 msg=“前三个字符应为数字” 去早退 如果结束 '检查中间字符,假设不区分大小写: 如果Instr(1,alpha,Lcase(Mid(strValue,4,1))=0,则 msg=“第四个字符应为连字符或字母” 去早退 如果结束 '检查最后四个字符 如果不是数字(右(标准值,4)),则 msg=“最后四个字符应为数字” 去早退 如果结束 '如果您已到达此处,则输入将被验证: 出口接头 提前退出: MsgBox味精 TextBox1.SetFocus 端接头
3个数字字符1个字母字符或1个连字符,然后5个数字字符

到目前为止您尝试了什么?无论如何,请查看此处以获取特定位置的字符:然后您可以测试字符,或者提取子字符串并分析它们(
IsNumeric()
等)@smagnan我已经有了以下内容:“如果TextBox1.Value=”“,则验证该框是否为空;如果TextBox1.Value=”“,则验证MsgBox(“抱歉,您需要提供金额”)TextBox1.SetFocus退出子端如果“如果”验证该框是否为数字,如果不是数字(TextBox1.Value),则验证MsgBox(“抱歉,必须输入数字”)TextBox1.SetFocus Exit Sub-End如果但后来我意识到我必须考虑第4个位置的字母或连字符,因此我需要更改代码,但我对此不熟悉,因此不确定如何执行,但我将能够执行get char方法,谢谢