【问题标题】:Validating the format of a userform textbox entry验证用户表单文本框条目的格式
【发布时间】:2015-06-08 19:18:34
【问题描述】:

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

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 

但后来我意识到我的问题是第四个位置可能有字母字符或连字符。

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

提前致谢。

【问题讨论】:

  • 到目前为止你尝试过什么?无论如何,请看这里以获取某些位置的字符:stackoverflow.com/questions/17127272/… 然后您可以测试字符,或者您可以提取子字符串并分析它们(IsNumeric() 等 ...)
  • @smagnan 我已经有以下内容:'验证该框不为空 If TextBox1.Value = "" Then MsgBox ("Sorry, you need 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 但是我意识到我必须考虑字母或连字符排在第 4 位,所以我需要更改代码,但我是新手,所以不确定如何操作,不过我可以使用 get-char 方法,所以谢谢

标签: validation excel textbox userform vba


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-03
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    相关资源
    最近更新 更多