EXCEL几行代码实现多条件筛选,让志愿填报变得轻松简单!
- 2026-11-09 05:04:36

Sub 筛选()
'关闭屏幕刷新
Application.ScreenUpdating = False
'声明变量,规范写法避免变体类型报错
Dim N As Long, i As Long
Dim regEx1 As Object, regEx2 As Object, regEx3 As Object, regex4 As Object
'获取A列最后一行数据行号
N = Cells(Rows.Count, "A").End(xlUp).Row
'以第10行为表头,A列精确匹配#@,先全部隐藏数据行
Rows(10).AutoFilter 1, "=#@"
'创建正则对象1,匹配规则取自B2单元格
Set regEx1 = CreateObject("VBSCRIPT.REGEXP")
With regEx1
.Global = True
.Pattern = Range("B2").Value
End With
'创建正则对象2,匹配规则取自B3单元格
Set regEx2 = CreateObject("VBSCRIPT.REGEXP")
With regEx2
.Global = True
.Pattern = Range("B3").Value
End With
'创建正则对象3,匹配规则取自B5单元格
Set regEx3 = CreateObject("VBSCRIPT.REGEXP")
With regEx3
.Global = True
.Pattern = Range("B5").Value
End With
'创建正则对象4,匹配规则取自B4单元格
Set regex4 = CreateObject("VBSCRIPT.REGEXP")
With regex4
.Global = True
.Pattern = Range("B4").Value
End With
'循环遍历11行至最后数据行
For i = 11 To N
'条件1:F列满足regEx1 且 不满足regEx2
If regEx1.Test(Cells(i, 6)) = True And regEx2.Test(Cells(i, 6)) = False Then
On Error Resume Next '数值为空/非数字时屏蔽报错
'条件2:J列数值在B6~B7区间内
If Cells(i, 10) >= Range("B6").Value And Cells(i, 10) <= Range("B7").Value Then
'条件3:C列匹配regEx3 且 E列匹配regex4
If regEx3.Test(Cells(i, 3)) = True And regex4.Test(Cells(i, 5)) = True Then
Rows(i).Hidden = False '满足全部条件,显示该行
End If
End If
On Error GoTo 0 '关闭错误忽略
End If
Next i
'释放正则对象,释放内存
Set regEx1 = Nothing
Set regEx2 = Nothing
Set regEx3 = Nothing
Set regex4 = Nothing
'打开屏幕刷新
Application.ScreenUpdating = True
End Sub
使用方法:
ALT+F11打开VBA编辑器,新建模块,将上述代码复制到模块中,点击运行即可!最后保存时,请另保存为EXCEL 启用宏的工作薄.XLSM格式。
本代码使用了正则表达式匹配,先隐藏所有行,再逐个显示符合条件的行,可以一次型筛选出符号条件的所有记录。如需更改筛选条件,改完后,重新运行一遍程序即可实现。
如果有需要,可以直接操作起来,或转发你身边正值高考志愿填报的同事、家长。