假设我在第1行中的这些值在任意列中:
1 A
2 A
3 A
4 A
5 B
6 B
7 B
8 A
9 A
10 A
Run Code Online (Sandbox Code Playgroud)
我希望能够说start = 5是第一个B而last = 7是最后一个B.如果没有B的第一个和最后一个返回0.
thd*_*oan 13
不要忘记,在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
Run Code Online (Sandbox Code Playgroud)
这样的东西适合你还是你需要两个单独的功能?
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
Run Code Online (Sandbox Code Playgroud)
像这样使用:
Dim rng As Range
Set rng = Range("B1:B10")
Dim i As Integer
i = findValues("first", "B", rng)
i = findValues("last", "B", rng)
Run Code Online (Sandbox Code Playgroud)
根据您需要检查的范围有多大,这可能需要一段时间。