Excel VBA代码

我是新来编写VBA代码,并在网上遇到这个代码,这是非常类似于我正在做的。 然而,当我尝试运行它时,它突出显示了Loop While Not c Is Nothing And c.Address <> firstAddress和一个消息popup说:“对象variables或块variables未设置”。

有谁知道如何解决这一问题? 任何帮助深表感谢!

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

问题在于你正在寻找数字2并将其更改为5.一旦它们全部被更改,它将继续在循环内从顶部继续search,但c将不会等于(因为它找不到任何东西)在第二次尝试评估c.Address <> firstAddress时,会导致错误。

当你replace的数字,我会删除该部分,只留下Loop While Not c Is Nothing

另一方面,如果你不改变值,只是寻找它们,你需要包含c.Address <> firstAddress来阻止它陷入无限循环。