楼主 amulee |
Q:如何编写自定义函数验证身份证号码的合法性? A:验证身份证号码要进行多个判断,要验证区域码是否合法,出生日期是否合法,校验码是否合法。本例中对上述几项进行验证判断。由于区域码数据库可能不完全,所以可以不考虑该验证。参考代码如下:
- Function IsIDNumber(ByVal IDNumber As String) As Boolean
- Dim SumM&
- Dim strTemp$
- '将英文转换成大写
- IDNumber = UCase(Trim(IDNumber))
- '先看前N位,不是数字就退出
- If Not IsNumeric(Left(IDNumber, 17)) Then Exit Function
- ' '再看前6位,不在数据库退出。数据库仅作参考
- ' If Sheet2.Range("A:A").Find(Left(IDNumber, 6), lookat:=xlWhole) Is Nothing Then Exit Function
- '分别对待15位和18位,
- Select Case Len(IDNumber)
- '15位看日期
- Case 15
- strTemp = Mid(IDNumber, 7, 6)
- If strTemp = Format(DateSerial(Left(strTemp, 2), Mid(strTemp, 3, 2), Right(strTemp, 2)), "yymmdd") Then IsIDNumber = True
- '18位看校验码
- Case 18
- '看校验码是否符合范围
- If Not IDNumber Like "*[0-9X]" Then Exit Function
- '看日期
- strTemp = Mid(IDNumber, 7, 8)
- If strTemp <> Format(DateSerial(Left(strTemp, 4), Mid(strTemp, 5, 2), Right(strTemp, 2)), "yyyymmdd") Then Exit Function
- '看校验码是否正确
- For i = 1 To 17
- SumM = CInt(Mid(IDNumber, i, 1)) * 2 ^ (18 - i) + SumM
- Next
- If Right(IDNumber, 1) = Mid("10X98765432", (SumM Mod 11) + 1, 1) Then IsIDNumber = True
- Case Else
- End Select
- End Function
附件下载: 身份证号码验证.rar |