【问题标题】:Using excel Range Find and FindNext to iterate over a range使用 excel Range Find 和 FindNext 遍历一个范围
【发布时间】:2018-06-10 17:08:11
【问题描述】:

很久以后我又回到了 VBA,并试图实现一个循环来查找多次出现的值。我挣扎了一下,用拖网拖网。我找到了这个例子;

Sub Button1_Click()
    With Worksheets(1).Range("a1:a50")
        Set c = .Find(2, LookIn:=xlValues)
        If Not c Is Nothing Then
            firstAddress = c.Address
            Do
                c.Value = 99
                Set c = .FindNext(c)
            Loop While Not c Is Nothing And c.Address <> firstAddress
        End If
    End With
End Sub

这来自 MSDN (https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-find-method-excel),所以我倾向于认为这是一个很好的例子。我重新设计了这个以适合我的应用程序,但出现了错误。然后我尝试直接运行 MSDN 给出的示例。我得到了同样的错误,如下所示。出现这种情况就行了

Loop While Not c Is Nothing And c.Address <> firstAddress

Error

任何人都可以对此有所了解。我真的很惊讶 MSDN 示例不起作用。

感谢期待

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    你会认为它会,但他们从来没有费心去纠正它。问题是您要删除 2 的所有实例,因此 c 最终是 Nothing 并且代码正在尝试检查 Nothing 的地址(因此出现错误)。您只需检查 c 是否为 Nothing。

    顺便说一句,您可以使用查找和替换来完成此操作。

    Sub Button1_Click()
        With Worksheets(1).Range("a1:a50")
            Set c = .Find(2, LookIn:=xlValues)
            If Not c Is Nothing Then
                Do
                    c.Value = 99
                    Set c = .FindNext(c)
                Loop While Not c Is Nothing
            End If
        End With
    End Sub
    

    【讨论】:

    • 您当然是完全正确的。这现在有效。有点明显,现在你看看它:-)。谢谢
    • 值得注意的是 Range Find 函数会回绕,因此您需要将自己的机制添加到循环中以防止这种情况发生。这显然是微软在他们的例子中试图做的,例如。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 2019-11-14
    • 1970-01-01
    相关资源
    最近更新 更多