|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
- Dim ws As Worksheet
- Set ws = ActiveSheet ' 使用当前活跃的工作表
-
- Dim namesArray As Variant
- namesArray = Array("张三1", "李四2", "王五3") ' 定义需要保留的名字数组,根据需要添加或删除名字
-
- Dim lastRow As Long
- lastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row ' 找到B列最后一个非空单元格的行号
-
- Dim i As Long, rngDel As Range
- Dim name As Variant, bFound As Boolean
- For i = lastRow To 4 Step -1 ' 从最后一行反向遍历到第4行
- bFound = False
- For Each name In namesArray ' 遍历名字数组
- If InStr(1, ws.Cells(i, "B").Value, name, vbTextCompare) > 0 Then ' 检查B列是否包含数组中的任何一个名字
- bFound = True ' 匹配成功
- Exit For ' 如果找到匹配的名字,则跳出内层循环,保留该行
- End If
- Next name
- If Not bFound Then ' 如果内层循环结束时name未改变,说明没找到匹配项,可以删除该行
- ' 待删除行保存到rngDel
- If rngDel Is Nothing Then
- Set rngDel = ws.Cells(i, "B")
- Else
- Set rngDel = Application.Union(rngDel, ws.Cells(i, "B"))
- End If
- End If
- Next i
- ' 一次行删除多行,效率更高
- If Not rngDel Is Nothing Then
- rngDel.EntireRow.Delete
- End If
- End Sub
复制代码 |
|