excel - 使用 vba 在 excel 范围内查找特定行
问题描述
我需要在工作表上找到满足给定条件的行。我多次看到作者通过根据搜索条件进行过滤来执行此操作,但我不喜欢这种方法,所以我使用了类似的方法。
Sub fi()
Dim lastRow As Long
lastRow = 100
Dim myRow As Long
For i = 1 To lastRow
If Cells(i, 1) = "value1" And Cells(i, 3) = "value2" And Cells(i, 4) = "value3" Then
i = myRow
End If
Next i
End Sub
你们有没有一些好的做法可以以更有效的方式做到这一点?这些是一种按行包含 10 个单元格的订单,但我可以根据其中三个找到我需要的东西。这是典型的 sql select 语句,但这里我不能使用 sql。谢谢
解决方案
试试这个(代码中的必要注释):
Sub fi()
Dim lastRow As Long, foundRange As Range
'this will find last row for you, don't need to hard-code it
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
'I used nested ifs, as it will boost the performance
'it will stop checking next conditions if preceding condition fail
For i = 1 To lastRow
If Cells(i, 1) = "value1" Then
If Cells(i, 3) = "value2" Then
If Cells(i, 4) = "value3" Then
'add columns A through J to foundRange
If foundRange Is Nothing Then
Set foundRange = Range(Cells(i, 1), Cells(i, 10))
Else
Set foundRange = Union(foundRange, Range(Cells(i, 1), Cells(i, 10)))
End If
End If
End If
End If
Next i
foundRange.Select
End Sub
推荐阅读
- rest - 使用 OPTIONS 的 RESTful API 授权/权限
- angular - Angular 5:如何从具有checked = true属性的数组中获取要在编辑组件上选中的复选框?
- python - Initializing state on dask-distributed workers
- php - 有 XML 的 SQL 吗?
- javascript - Angular 7导入所有但忽略一个文件
- android - 以编程方式重新初始化后,线性布局内的视图无法正确显示
- nginx - 具有相似前缀的 nginx 位置
- java - 新标签导航有时不加载页面,为什么?
- c - SDL Init 在代码正确且之前运行完美时减慢程序
- c++ - Simplest way to determine if current assembly is 32/64bit within the code