我试图在Excel工作表的列中找到特定值,然后在右侧添加一个值(= 1)三列。
我的代码:
Sub AddNote()
ActiveSheet.Range("F:F").Find(What:="Cat").Select
Selection.Offset(0, 4).Value = 1
End Sub
只有我得到了:
错误消息91:`对象变量或未设置块变量。
我的命令出了什么问题?
答案 0 :(得分:5)
看看这个:
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
答案 1 :(得分:2)
错误消息91:`对象变量或未设置块变量。
这个错误意味着搜索失败,没有&#34; Cat&#34;在专栏
试试这个:
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
还有一条评论,避免使用select
和selection
方法,这是不好的做法
答案 2 :(得分:0)
如果.Find
方法没有输出范围(&#34; Cat&#34;不匹配),那么.Offset
方法将停止错误。
结构化解决方案将遵循:
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