VBA.Find并添加一个值

我试图在Excel工作表的一列中find一个特定的值,然后在右边添加一个值(= 1)三列。

我的代码:

Sub AddNote() ActiveSheet.Range("F:F").Find(What:="Cat").Select Selection.Offset(0, 4).Value = 1 End Sub 

只有我得到了:

错误信息91:`对象variables或块variables未设置。

我的命令有什么问题?

看看这个 :

 Sub test_IngaB() Dim FirstAddress As String, cF As Range, LookForString As String LookForString = "Cat" With ThisWorkBook.Sheets("Sheet's name").Range("F:F") .Cells(1,1).Activate 'First, define properly the Find method Set cF = .Find(What:=LookForString, _ After:=ActiveCell, _ LookIn:=xlFormulas, _ LookAt:=xlPart, _ SearchOrder:=xlByColumns, _ SearchDirection:=xlNext, _ MatchCase:=False, _ SearchFormat:=False) 'If there is a result, keep looking with FindNext method If Not cF Is Nothing Then FirstAddress = cF.Address Do cF.Offset(0, 3).Value = 1 Set cF = .FindNext(cF) 'Look until you find again the first result Loop While Not cF Is Nothing And cF.Address <> FirstAddress End If End With End Sub 

错误信息91:`对象variables或块variables未设置。

这个错误意味着search失败,列中没有“Cat”

尝试这个:

 Sub test() Dim rng As Range Set rng = ActiveSheet.[F:F].Find("Cat") If Not rng Is Nothing Then rng.Offset(, 4).Value = 1 Else MsgBox "Searching criteria does not exists in column [F]!" End If End Sub 

还有一点意见,避免使用selectselection方法,这是不好的做法

如果.Find方法不输出一个范围(没有匹配“Cat”),那么.Offset方法将会暂停一个错误。

一个结构化的解决scheme将是:

 Sub AddNote() Dim rng As Range Set rng = ActiveSheet.Range("F:F") If Application.WorksheetFunction.CountIfs(rng, "*Cat*") <> 0 Then 'if there is a match for "Cat" (LookAt:=xlPart), if you want exact matches, remove the asterisks rng.Find(What:="Cat").Select Selection.Offset(0, 4).Value = 1 End If End Sub