|
楼主 |
发表于 2024-8-2 19:17
|
显示全部楼层
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
Sub CheckIDs()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1") ' 修改为你的工作表名
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row ' 找到A列的最后一个非空行
Dim i As Long
Dim id As String
Dim isValid As Boolean
Dim outputRow As Long
outputRow = 1 ' 从B1开始输出不符合条件的身份证号
For i = 1 To lastRow
id = ws.Cells(i, 1).Value ' 读取A列的身份证号
isValid = CheckIDValidity(id) ' 调用函数检查身份证号是否有效
If Not isValid Then
' 如果身份证号不符合条件,则复制到B列
ws.Cells(outputRow, 2).Value = id
outputRow = outputRow + 1 ' 更新输出行的位置
End If
Next i
End Sub
' 检查单个身份证号是否有效的函数
Function CheckIDValidity(ByVal id As String) As Boolean
Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")
With regex
.Pattern = "^(\d{17}[\dXx])$" ' 匹配17位数字加一位数字或X的模式
.Global = True
.IgnoreCase = False
If .Test(id) Then
' 如果匹配,返回True
CheckIDValidity = True
Else
' 如果不匹配,返回False
CheckIDValidity = False
End If
End With
End Function
Function CalculateIDCheckDigit(ByVal idPrefix As String) As String
' 确保输入的是17位数字
If Len(idPrefix) <> 17 Or Not IsNumeric(idPrefix) Then
CalculateIDCheckDigit = "Error: Invalid input"
Exit Function
End If
' 加权因子数组,对应身份证前17位
Dim weights() As Integer
weights = Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2)
' 校验码对应的字符数组
Dim checkChars() As String
checkChars = Array("1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2")
' 计算加权和
Dim sum As Integer
Dim i As Integer
For i = 0 To 16
sum = sum + Val(Mid(idPrefix, i + 1, 1)) * weights(i)
Next i
' 计算校验码
Dim modValue As Integer
modValue = sum Mod 11
' 返回校验码
CalculateIDCheckDigit = checkChars(modValue)
End Function
这些代码,都不知怎么写的。 |
|