简体   繁体   English

根据单元格值查找行的功能

[英]Function to find row based on cell value

I have the following code to find the row where a certain value resides, however it keeps debugging with 我有以下代码来查找特定值所在的行,但是它会不断调试

Error 91 "Object variable or With block variable not set" 错误91“未设置对象变量或带块变量”

Which is weird because I use the same structure to find a row before this procedure and it works. 这很奇怪,因为在此过程之前,我使用相同的结构来查找行,并且该行有效。

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

Your only problem is that when you don't have "Name" on your worksheet .Find returns Nothing rather than a Range object. 唯一的问题是,当您的工作表上没有“名称”时。 .Find将返回Nothing而不是Range对象。 You then get an error because you are trying to use .Activate on Nothing . 然后,您将收到错误消息,因为您尝试在Nothing上使用.Activate

The solution 解决方案

There is no need to use Activate and ActiveCell , just define your variables well and use them! 无需使用ActivateActiveCell ,只需定义好变量并使用它们即可! Here's a working example: 这是一个工作示例:

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

Apparently there was a space after "Name", so I should have been looking for "Name ". 显然在“名称”之后有一个空格,因此我应该一直在寻找“名称”。 Revised the search and it worked the way I had it but thank you @CallumDA for your clean answer. 修改了搜索,它按照我的方式工作,但是感谢@CallumDA的简洁回答。 So my problem is that it was not able to find my lookup variable which in turn meant it could not activate the found cell resulting in the Error 91! 所以我的问题是,它找不到我的查找变量,这反过来又意味着它无法激活找到的单元格,从而导致错误91! Much appreciated for your quick reply. 非常感谢您的快速回复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM