![](/img/trans.png)
[英]excel/vba - find fist and last occurrence of a particular value in a column
[英]Excel VBA: Return first occurrence of a word in a column? The last?
假設我在第1行中的這些值在任意列中:
1 A
2 A
3 A
4 A
5 B
6 B
7 B
8 A
9 A
10 A
我希望能夠說start = 5是第一個B而last = 7是最后一個B.如果沒有B的第一個和最后一個返回0。
不要忘記,在VBA中,您仍然可以訪問大量內置的Excel功能。 示例(假設您的數據在第1列中):
找到第一個B ......
Columns(1).Find(What:="B", LookAt:=xlWhole, MatchCase:=False).Row 'Returns 5
找到最后一個B ...
Columns(1).Find(What:="B", LookAt:=xlWhole, SearchDirection:=xlPrevious, MatchCase:=False).Row 'Returns 7
如果未找到B,則返回錯誤。 如果找不到B,我們可以通過使用錯誤處理來返回0來利用這一點。 把它們放在一起......
Sub DoTest()
Dim RowFirst As Integer, _
RowLast As Integer
On Error GoTo ErrorHandler
RowFirst = Columns(1).Find(What:="B", LookAt:=xlWhole, SearchDirection:=xlNext, MatchCase:=False).Row
RowLast = Columns(1).Find(What:="B", LookAt:=xlWhole, SearchDirection:=xlPrevious, MatchCase:=False).Row
Exit Sub
ErrorHandler:
RowFirst = 0
RowLast = 0
End Sub
這樣的事情對你有用還是需要兩個獨立的功能?
Function findValues(place As String, val As String, rng As Range) As Integer
Dim r As Range
findValues = 0
For Each r In rng
If InStr(r.Value2, val) > 0 Then
findValues = r.Row
If LCase(place) = "first" Then
Exit For
End If
End If
Next
End Function
使用這樣:
Dim rng As Range
Set rng = Range("B1:B10")
Dim i As Integer
i = findValues("first", "B", rng)
i = findValues("last", "B", rng)
根據您需要檢查的范圍有多大,這可能需要一段時間。
這是另一種方式。
Sub FindFirstLast()
Dim vaValues As Variant
Dim vaFilter As Variant
Dim lFirst As Long
Dim lLast As Long
Const sFIND As String = "B"
With Application.WorksheetFunction
'Get a 1-d array from a column
vaValues = .Transpose(Sheet1.Range("A1:A10").Value)
'Use match to get the first instance
lFirst = .Match(sFIND, vaValues, False)
'Filter on the values
vaFilter = Filter(vaValues, sFIND)
'Assumes they're all together
lLast = lFirst + UBound(vaFilter)
End With
Debug.Print lFirst, lLast
End Sub
我在一些應用程序中一直使用Kevin Pope的方法,但發現它有時會包含我不想要的東西。 以為我會分享我的經驗和解決方案。
最近我意識到,如果我有這樣的事情:
Mouser EPM1270GT144I5
Mouser EPM1270GT144I5
Mouser GRM32DR71E106K
Mouser GRM32DR71E106K
TTI GRM32DR71E106KA12L
Avnet GS816273CC-250I
Avnet GS816273CC-250I
並在尋找:GRM32DR71E106K
它會返回我正在搜索的兩個,第三個以相同的字符串開頭。
我需要適應搜索精確匹配。 修復非常簡單:
Public Function findValues(Val As String, Rng As Range, Optional place As Integer) As Integer
Dim R As Range
findValues = 0
For Each R In Rng
If StrComp(R.Value2, Val) = 0 Then
' If InStr(R.Value2, Val) > 0 Then
findValues = R.Row
If place = 1 Then
Exit For
End If
End If
Next
End Function
我希望有人覺得有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.