Excel VBA range.find表演

我试图使用range.find查找列中的值,并返回下一列的匹配值。

我使用macroslogging器logging了find(),这似乎在一段时间内工作正常,但由于某种原因,现在给我一个错误。 据我所知,我没有改变任何应该影响这一点的代码。

这是我的

Public Function look_up_id(id, table) Worksheets(table).Activate Cells.Find(What:=id, After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate look_up_id = ActiveCell.Offset(0, 1).Value End Function 

我现在得到的错误是:

对象variables或未设置块variables

任何想法为什么这是现在发生?

所有的资源,我可以在range.find()看起来像我做对了…

干杯 – 大卫

尝试这个

 Public Function look_up_id(id, table) As Variant Dim ws As Worksheet Dim aCell As Range look_up_id = "Not Found" Set ws = ThisWorkbook.Sheets(table) With ws Set aCell = .Cells.Find(What:=id, _ LookIn:=xlFormulas, _ LookAt:=xlPart, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False, _ SearchFormat:=False) If Not aCell Is Nothing Then _ look_up_id = aCell.Offset(, 1).Value End With End Function 

更多关于。find这里

尝试使用这个代码来代替(当Find没有find任何东西时,它返回Nothing ,然后你试图做这样的Nothing.Activate ,这会触发一个错误):

 Dim res As Range Set res = Worksheets(table).Cells.Find(What:=id, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False) If Not res Is Nothing Then look_up_id = res.Offset(0, 1).Value End If