【问题标题】:.FindNext failing after a .Find function (excel vba).FindNext 在 .Find 函数后失败(excel vba)
【发布时间】:2012-06-14 17:24:30
【问题描述】:

我正在尝试使用.Find.FindNext 来搜索单列数据。我首先需要找到包含值“Total”的第一个单元格。我试图到达的单元格是“总计”单元格之后的第三个单元格,其中包含值“技术”。可以肯定的是 Cells(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 还是很陌生,到目前为止我发现没有任何资源可以回答这个问题。请帮忙!

【问题讨论】:

  • Range.FindNext 似乎最终被打破了。即使使用与 Microsoft 示例相同的代码,它也从未对我有用。

标签: excel find next vba


【解决方案1】:

如果未找到“Total”,则 FirstTotal 将为 Nothing,当您尝试将 FirstTotal 用于 ResultRange Find(第 2 行)中的“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 语句,但我不知道那会是什么。

【讨论】:

  • 根据我提交的一些调试通知,FirstTotal 大约 50% 的时间设置正确,其余时间为空。代码中在此之前没有其他 .Find 或 .FindNext 调用。您能想到发生这种情况的任何原因吗?
  • 我们知道这意味着找不到“Total”。这意味着 SearchRange 不包含“总计”。当找不到“Total”时,我会看看 SearchRange 的地址是什么。
【解决方案2】:

这会有帮助吗?

主题:Excel VBA中的.Find和.FindNext

链接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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多