[英]Find a specific row in a excel range with vba
I need to find rows on a sheet that meet given criteria(s).我需要在工作表上找到满足给定条件的行。 I saw several times that authors perform this by filtering based on the search criteria but I don't like this method, so I am using something like this.
我多次看到作者通过根据搜索条件过滤来执行此操作,但我不喜欢这种方法,因此我使用了类似的方法。
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
Does any of you have some good practice to do it on more efficient way?你们中有没有人有一些好的做法来以更有效的方式做到这一点? These are a kind of orders with 10 cells by row, but I can find what I need based on three of them.
这些是一种一行 10 个单元格的订单,但我可以根据其中的三个找到我需要的东西。 It is s typical sql select statement, but here I cannot use sql.
这是典型的 sql select 语句,但在这里我不能使用 sql。 thanks
谢谢
You could use the following approach with ADODB您可以在 ADODB 中使用以下方法
Option Explicit
Sub ReadFromWorksheetADO()
Dim conn As New ADODB.Connection
' Assuming there is no header
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
& ThisWorkbook.FullName & ";Extended Properties=""Excel 12.0;HDR=NO;"";"
Dim query As String
' The sheet with the data should have the name Sheet1
' query = "Select * From [Sheet1$]"
query = "Select F1,F2,F3 From [Sheet1$]"
Dim rs As New ADODB.Recordset
rs.Open query, conn
rs.Filter = "F1='value1' AND F2 ='value2' AND F3 ='value'"
' Add a sheet with codename shResult
' only needed for test purposes
' to show the result
With shResult
.Cells.ClearContents
Dim i As Long
For i = 0 To rs.Fields.Count - 1
.Cells(1, i + 1).Value = rs.Fields(i).Name
Next i
.Range("A2").CopyFromRecordset rs
End With
End Sub
Try this (necessary comments in code):试试这个(代码中必要的注释):
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.