|
楼主 |
发表于 2016-7-6 23:21
|
显示全部楼层
下列代码来自本站,有所修改,谢谢原作者:
Function idtest(theid)
Dim arr As Variant, brr() As Variant, a As Variant, b As Variant, theFinalRow&, id
Dim i&, j&, theSum&, theNum&, theStr$, theDate As Date, theYear&, theMonth&, theDay&, theAge&
idtest = "身份证校验通过"
theDate = Date
a = VBA.Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2)
b = VBA.Array("1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2")
theSum = 0
If theid <> "" Then
If Len(theid) = 18 Then
For j = 1 To 17
theSum = theSum + CLng(Mid(theid, j, 1)) * a(j - 1)
Next j
theNum = theSum Mod 11
If UCase(Right(theid, 1)) <> b(theNum) Then
idtest = "身份证校验码不正确"
Else
theYear = Mid(theid, 7, 4)
theMonth = Mid(theid, 11, 2)
theDay = Mid(theid, 13, 2)
theStr = theYear & "-" & theMonth & "-" & theDay
If Not IsDate(theStr) Then
idtest = "身份证日期有误"
Else
theAge = DateDiff("yyyy", CDate(theStr), theDate)
If theAge < 0 Or theAge > 130 Then '小于0岁或大于130岁判为不正常
idtest = "身份证日期不正常"
End If
End If
End If
Else
idtest = "身份证长度不正确"
End If
End If
If idtest = "身份证校验通过" Then
theYear = Mid(theid, 7, 4)
theMonth = Mid(theid, 11, 2)
theDay = Mid(theid, 13, 2)
theStr = theYear & "-" & theMonth & "-" & theDay
theAge = DateDiff("yyyy", CDate(theStr), theDate)
idtest = theAge & "|" & idtest
End If
End Function
补充内容 (2017-4-13 11:02):
Function IDcheck(ID) '身份证号码校验函数
Dim s, i As Integer
Dim e, z As String
Part1: '----------------------------身份证号码合法性检查---------------------------------------
If Not (Len(ID) = 18 Or Len(ID) = 15) Then '位数检验
IDcheck = "位数错误"
Exit Function
Else
If Len(ID) = 15 Then ID = Left(ID, 6) & "19" & Right(ID, 9)
If IsNumeric(Left(ID, 17)) = False Or InStr(ID, ".") > 0 Then '字符检验
IDcheck = "字符错误"
Exit Function
End If
On Error Resume Next '日期检验
If DateValue(Mid(ID, 7, 4) & "-" & Mid(ID, 11, 2) & "-" & Mid(ID, 13, 2)) < 1 Or _
DateValue(Mid(ID, 7, 4) & "-" & Mid(ID, 11, 2) & "-" & Mid(ID, 13, 2)) > Date Then
IDcheck = "日期错误"
Exit Function
End If
End If
Part2: '-----------------------------校验码的生成及检查----------------------------------------
s = 0
For i = 1 To 17
s = s + Val(Mid(ID, 18 - i, 1)) * (2 ^ i Mod 11)
Next
e = Mid("10X98765432", (s Mod 11) + 1, 1) '生成校验码
If Len(ID) = 18 Then
z = UCase(Right(ID, 1))
If z = e Then '校验码对比
IDcheck = "通过"
Else
IDcheck = "校验未通过" '如果要返回校验码,请把本行语句改为:IDcheck = e
End If
Else
IDcheck = "通过" 'ID & e '15位身份证号码升位
End If
End Function
|
|