所以,我有一个工作表,我想在Range(“A:A”)中搜索Range(“M”& i)的值。但是,当我尝试运行此代码时,它会返回错误:“运行时错误'91':对象变量或未设置块。当我单击调试时,它会在
上发现错误 SearchIn = Range("A:A")
我确实谷歌互联网和这个网站(发现了一些东西),但我仍然无法解决问题。有人知道吗?
Sub Find_Replace()
Dim i As Integer
Dim SearchIn As Range
Dim SearchedObject As Range
Dim FinalCell As Range
Dim SumCell As Range
i = 5
SearchIn = Range("A1:A740")
StartSearch = Range("A" & i)
FinalCell = Range("N" & i)
Do While i <= 740
SearchedObject = SearchIn.Find(What:="M" & i, After:=StartSearch, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
If SearchedObject.Value = Range("M" & i).Value Then FinalCell = FinalCell.Value + SearchedObject.Offset(0, 5).Value
Loop
End Sub
答案 0 :(得分:11)
我还没有测试过,但这是你想要做的吗?
分配范围时,您必须使用SET
Sub Find_Replace()
Dim i As Integer
Dim SearchIn As Range
Dim SearchedObject As Range
Dim FinalCell As Range
Dim SumCell As Range
i = 5
Set SearchIn = Range("A1:A740")
Set StartSearch = Range("A" & i)
Set FinalCell = Range("N" & i)
Do While i <= 740
Set SearchedObject = SearchIn.Find(What:="M" & i, After:=StartSearch, _
LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
If Not SearchedObject Is Nothing Then
If SearchedObject.Value = Range("M" & i).Value Then _
FinalCell.Value = FinalCell.Value + SearchedObject.Offset(0, 5).Value
End If
Loop
End Sub
编辑:另外建议使用完整路径,否则搜索将始终在活动工作表中进行
例如
Set SearchIn = Sheets("Sheet1").Range("A1:A740")
与其他人相似。