MS Excel的VBA – 查找function获取行

目前有下面的代码来查找一个特定的值所在的行,但它保持debugging

错误91“对象variables或块variables未设置”

这是很奇怪的,因为我使用相同的确切结构在这个过程之前find一行,它的工作原理是完美的。 任何提示,将不胜感激!

wbs.Activate Cells.Find(What:="Name", After:=wbs.Range("A1"), LookIn:=xlFormulas, _ LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=True, SearchFormat:=False).Activate NameRow = ActiveCell.Row 

更新:请参阅下面的“我的答案”

你唯一的问题是,当你的工作表上没有“Name”的时候.Find返回Nothing而不是Range对象。 然后你会得到一个错误,因为你正在尝试使用.Activate Nothing

解决scheme

没有必要使用ActivateActiveCell ,只需定义你的variables并使用它们! 这是一个工作的例子:

 Sub test() Dim wks As Worksheet Dim r As Range Dim rowNumber As Long Set wks = ThisWorkbook.Worksheets("sheet1") 'update for your worksheet name '.Find returns a Range object or Nothing Set r = wks.Cells.Find(What:="Name", LookAt:=xlWhole) If Not r Is Nothing Then rowNumber = r.Row End If MsgBox rowNumber End Sub 

显然“姓名”之后有一个空格,所以我应该一直在寻找“姓名”。 修改search,它的工作方式,我有它,但谢谢@CallumDA你干净的答案。 所以我的问题是,它无法find我的查找variables,这反过来又意味着它不能激活find的单元格导致错误91! 非常感谢您的快速回复。