发现导出的手机号,有部分存在问题,故想直接通过excel做正则的判断
先说结论:通过VBA实现了正则函数的嵌入,但实际效率非常低下,80万的数据跑了半小时(T14 十代i7)
参考文章:正则表达式直接在EXCEL中使用的详细步骤_正则表达式_脚本之家
第一步,找到VAB的函数(百度找的,找不到来源了)
- Public Function RegExpMatch(input_range As Range, pattern As String, Optional match_case As Boolean = True) As Variant
-
- '存储结果的数组
-
- Dim arRes() As Variant
-
- '源单元格区域中当前行索引值
-
- '源单元格区域中当前列索引值
-
- '行数, 列数
-
- Dim iInputCurRow As Long
-
- Dim iInputCurCol As Long
-
- Dim cntInputRows As Long
-
- Dim cntInputCols As Long
-
- On Error GoTo ErrHandl
-
- RegExpMatch = arRes
-
-
-
- Set regex = CreateObject("VBScript.RegExp")
-
-
-
- regex.pattern = pattern
-
- regex.Global = True
-
- regex.MultiLine = True
-
-
-
- If True = match_case Then
-
- regex.ignorecase = False
-
- Else
-
- regex.ignorecase = True
-
- End If
-
-
-
- cntInputRows = input_range.Rows.Count
-
- cntInputCols = input_range.Columns.Count
-
- ReDim arRes(1 To cntInputRows, 1 To cntInputCols)
-
-
-
- For iInputCurRow = 1 To cntInputRows
-
- For iInputCurCol = 1 To cntInputCols
-
- arRes(iInputCurRow, iInputCurCol) = regex.Test(input_range.Cells(iInputCurRow, iInputCurCol).Value)
-
- Next
-
- Next
-
-
-
- RegExpMatch = arRes
-
- Exit Function
-
-
-
- ErrHandl:
-
- RegExpMatch = CVErr(xlErrValue)
-
- End Function
第二步,嵌入到Excel中,顺序如下:
下面我们使用的这个方法,定义出的函数将长期有效:
1、新建一个EXCEL文件,我这里命名为RE,随后按ALT+F11打开宏编辑器,选中任意一个sheet,右键,选择插入模块:

2、双击模块1,编辑如第一步的VBA自定义函数代码
3、另存为加载宏格式:

4、点击下方的加载项:(不同版本Excel可以百度如何打开开发工具以及如何打开加载项)

5、点击浏览:
6、选择我们刚保存的加载宏格式文件,结果如下图:
好了,到这里我们的正则函数就创建好了,随后每次打开EXCEL都可以直接使用定义的RegExpMatch函数,按照需求来敲出合适的正则表达式。
第三步,找一段手机号匹配的正则规则
^((\+?86)|(
\+ 86 " role="presentation" style="position: relative;">))?1[3-9]\d{9}$
#匹配前缀是86或者+86,第一位为1,第二位为3-9的数字,第三位开始有9位数字#
第四步,到excel使用函数
=RegExpMatch(A1,"^((\+?86)|(
\+ 86 " role="presentation" style="position: relative;">))?1[3-9]\d{9}$")

最终,对80万手机号进行了验证,花了大概半小时,而且每次打开都要重新跑一次(不过会快一点),建议跑完之后立即将结果复制成文本。