我正在尝试使用.Find
和.FindNext
来搜索单列数据。我首先需要找到包含值“Total”的第一个单元格。我试图获得的单元格是“Total”单元格后面包含值“Tech”的第三个单元格。已知确定细胞(1,1)不含“Tech”或“Total”。
Dim FirstTotal As Range
Dim SearchRng As Range
Dim ResultRng As Range
Set SearchRng = Range("A:A")
Set FirstTotal = SearchRng.Find(What:="Total", After:=Cells(1, 1), SearchDirection:=xlNext)
Set ResultRng = SearchRng.Find(What:="Tech", After:=FirstTotal, SearchDirection:=xlNext)
SearchRng.FindNext().Activate
SearchRng.FindNext().Activate
我运行此代码的时间大约有50%,我在Set ResultRng =
开头的行上遇到了类型不匹配错误。其余的时间,代码一直在运行,但结果看起来好像完全忽略了最后两行代码。
我怀疑这里的答案非常简单,但我很擅长excel vba,到目前为止我找不到的资源已经回答了这个问题。请帮忙!
答案 0 :(得分:1)
如果未找到“Total”,则FirstTotal将为Nothing,当您尝试在ResultRange Find(第2行)中使用FirstTotal作为“After”参数时,将导致类型不匹配。这样可以防止出现错误:
Set FirstTotal = SearchRng.Find(What:="Total", After:=Cells(1, 1), SearchDirection:=xlNext)
If Not FirstTotal is Nothing Then
Set ResultRng = SearchRng.Find(What:="Tech", After:=FirstTotal, SearchDirection:=xlNext)
End If
一般来说,任何依赖的Find都需要这样对待。
显然,这里需要某种Else声明,但我不知道那会是什么。
答案 1 :(得分:1)
这会有帮助吗?
主题:.Find和.FindNext在Excel VBA中
链接:http://www.siddharthrout.com/2011/07/14/find-and-findnext-in-excel-vba/
摘自链接:
Sub Sample()
Dim oRange As Range, aCell As Range, bCell As Range
Dim ws As Worksheet
Dim ExitLoop As Boolean
Dim SearchString As String, FoundAt As String
On Error GoTo Err
Set ws = Worksheets("Sheet3")
Set oRange = ws.Columns(1)
SearchString = "2"
Set aCell = oRange.Find(What:=SearchString, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
Set bCell = aCell
FoundAt = aCell.Address
Do While ExitLoop = False
Set aCell = oRange.FindNext(After:=aCell)
If Not aCell Is Nothing Then
If aCell.Address = bCell.Address Then Exit Do
FoundAt = FoundAt & ", " & aCell.Address
Else
ExitLoop = True
End If
Loop
Else
MsgBox SearchString & " not Found"
End If
MsgBox "The Search String has been found at these locations: " & FoundAt
Exit Sub
Err:
MsgBox Err.Description
End Sub