validationstringinput
我需要在Excel中validation社会安全号(SSN)。 我不知道从哪里开始,我已经在网上到处看,但无济于事…请帮助,如果可以的话。 谢谢。
以下是validation规则:
- 字段长度始终为9位数字。
- 不能是全部相同的数字(例如
222-22-2222
) - 不能包含从
1 to 9
或从9 to 1
连续数字(即123-45-6789
) - 不能包含数字以外的数字(
0-9
) - 受限制的数字以
666
开始。 - 不能包含9作为第一个数字
- 最后四位数字不能为零
(0000)
。
下面的正则expression式解决scheme,从这里吸取很大
我注意到这个情况
不能包含从1到9或从9到1的连续数字(即123-45-6789,9876-54-321)
已通过以下方式失效:
不能包含9作为第一个数字。
使用代码
- 按Alt F11进入可视化基本编辑器
- 插入 …. 模块
- 复制并粘贴从
Sub OCD_Kid()
开始的代码 - 按Alt F11返回到Excel
然后,您可以使用此用户定义的公式(UDF)直接testing电子表格中的值。
- 如果
A1
有070-22-2794
, - 在
B1
input=OCD_Kid(A1)
来testingA1
的string
主要代码
Function OCD_Kid(strIn As String) As Boolean Dim objRegex As Object Set objRegex = CreateObject("vbscript.regexp") With objRegex .Global = True .Pattern = "^(?!\b(\d)\1+-(\d)\1+-(\d)\1+\b)(?!123-45-6789)(?!666|000|9\d{2})\d{3}-\d{2}-(?!0{4})\d{4}$" OCD_Kid = .test(strIn) End With End Function
testing
Sub Tested() Debug.Print OCD_Kid("222-22-2222") ' Invalid Debug.Print OCD_Kid("070-22-2794") ' Valid Debug.Print OCD_Kid("823-45-6789") ' Valid Debug.Print OCD_Kid("123-45-6789") ' Invalid Debug.Print OCD_Kid("123-45-5789") ' Valid End Sub
这不是一个完整的答案。
但是,它会给你一个模板,你可以扩展以满足更多的标准。 这是一个用户定义函数(UDF)
Public Function SSNCheck(s As String) As String Dim i As Long SSNCheck = "Bad" If Len(s) <> 11 Then Exit Function ary = Split(s, "-") If UBound(ary) <> 2 Then Exit Function For i = 0 To 2 If Not IsNumeric(ary(i)) Then Exit Function Next i If Len(ary(0)) <> 3 Then Exit Function If Len(ary(1)) <> 2 Then Exit Function If Len(ary(2)) <> 4 Then Exit Function If ary(2) = "0000" Then Exit Function If ary(0) & ary(1) & ary(2) = "123456789" Then Exit Function SSNCheck = "Good" End Function
用户定义的函数(UDF)非常易于安装和使用:
- ALT-F11调出VBE窗口
- ALT-I ALT-M打开一个新的模块
- 粘贴东西,closuresVBE窗口
如果保存工作簿,则UDF将随之保存。 如果您在2003年以后使用的是Excel版本,则必须将该文件另存为.xlsm而不是.xlsx
要删除UDF:
- 如上所示调出VBE窗口
- 清除代码
- closuresVBE窗口
从Excel中使用UDF:
= SSNCheck(A1)
要了解有关macros的更多信息,请参阅:
http://www.mvps.org/dmcritchie/excel/getstarted.htm
和
http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx
和
http://www.cpearson.com/excel/WritingFunctionsInVBA.aspx
有关UDF的细节
macros必须启用这个工作!