excel - VBA 中的多个 Range.Find()

标签 excel vba excel-2007

我今天遇到了这个有趣的问题。我在另一个循环中有一个循环,并且都使用 Find 来实现不同的目的。发生的情况是,在内循环中使用 Find 会搞乱外循环上的 Find。我猜仅保留一个搜索实例的内存。有什么方法可以解决这个问题还是这是一个设计问题?

这是我的代码的一些缩短版本。

Sub Main()
    'Some boring stuff

    Set lst_rapports = Worksheets("mappingTRANSIT").range("lst_rapports")
    Set first_result = lst_rapports.Find(rap_choisi)
    Set active_result = first_result

    Sheets("req01").Unprotect "shoobidoowap"
    If Not first_result Is Nothing Then
        ' ...            
        Do
            Sheets("req01").Select            
            ' ...
            For i = 0 To 4
                Set rubrique_cell = range("E:E").Find(rub(i))
                If Not rubrique_cell Is Nothing Then
                    ' ...
                End If
            Next i                
            ' Yet more boring stuff...

            Set active_result = lst_rapports.FindNext(active_result)
        Loop Until active_result.Address = first_result.Address
    Else
        MsgBox "Impossible de trouver """ & rap_choisi & """ !"
    End If
    Sheets("req01").Protect "shoobidoowap"
End Sub

注意 for 循环中第二次使用 .Find

有什么方法可以将第一次搜索保留在某种临时变量中,然后再将其恢复吗?

非常感谢。

最佳答案

当您运行 FindNext (MSDN for FindNext) 时,它会自动使用与上次调用 Find 相同的 what,即使用于不同的范围。

要纠正此问题,请不要使用

设置 active_result = lst_rapports.FindNext(active_result)

使用

设置 active_result = lst_rapports.Find(rap_choisi,active_result)

关于excel - VBA 中的多个 Range.Find(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12807907/

相关文章:

vba - 如何让循环在 VBA 中工作?

excel - WinHttpRequest 对象返回 "â??"而不是 "✓"(U+2713)

vba - 如何将数组中的值暗淡为数组?

arrays - 在 Excel VBA 中将工作表名称添加到数组

regex - Excel 中的模式匹配计数(正则表达式和 VBA)

vba - 如何自动移动列表框上的滚动条以显示所选项目 - VBA

c# epplus 修改 excel 如何计算每列最后一个单元格的数量

excel - 范围限制公式的结果

Excel (2007) VBA - .Formula 包含引号

vba - 使用 Excel VBA 在单元格/字符串中查找 URL