找到的对象返回Nothing,尽管在“如果不是......什么都没有”检查中设置

问题描述 投票:0回答:2

我试图在一行中查找一个字符串,然后选择找到的单元格。为此,我有以下部分代码:

currentRelease = Worksheets("Summary").Cells(5, "I").Value
Set myrange = Worksheets("Summary").Rows(15)

If Not myrange.Find(currentRelease, lookat:=xlValues) Is Nothing Then
    Set releaseFound = myrange.Find(currentRelease, lookat:=xlValues) 'this row gets executed
    releaseFound.Select
End If

我没有收到任何错误,但是在调试时没有选择任何单元格,并且我看到

releaseFound
正在返回
Nothing
,尽管此代码的
Set releaseFound...
行被执行,因此
If
检查实际上是积极的?这可能是什么原因?
我尝试在 VBA 之外使用工作表上的
Find
功能,并且确实在我搜索的位置找到了该值...

excel vba find
2个回答
1
投票

查找方法示例

Option Explicit

Sub FindMethodTest()
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim ws As Worksheet: Set ws = wb.Worksheets("Summary")
    
    ' Try to restrict this declaration to a string or a numeric value.
    Dim SearchValue As Variant: SearchValue = ws.Cells(5, "I").Value
    
    Dim SearchRange As Range: Set SearchRange = ws.Rows(15)
    
    ' Use a variable to reference the found cell.
    Dim FirstFoundCell As Range
    ' To start the search with the first cell 'A15', you need to set
    ' the 'After' parameter to the last cell in row '15'.
    Set FirstFoundCell = SearchRange.Find( _
        What:=SearchValue, After:=SearchRange.Cells(SearchRange.Cells.Count), _
        LookIn:=xlValues, LookAt:=xlWhole)
        
    ' Now test the variable.
    If Not FirstFoundCell Is Nothing Then ' found
        FirstFoundCell.Select
        Debug.Print "The first found value is in cell '" _
            & FirstFoundCell.Address(0, 0) & "'."
    Else ' not found
        Debug.Print "Value not found."
    End If

End Sub

0
投票

@GSerg 在上面的评论中的建议解决了这个问题:lookat 接受 xlWhole 或 xlPart。 xlValues 进入 LookIn。 该代码现在对我有用:

currentRelease = Worksheets("Summary").Cells(5, "I").Value
Set myrange = Worksheets("Summary").Rows(15)

If Not myrange.Find(currentRelease, lookin:=xlValues) Is Nothing Then
    Set releaseFound = myrange.Find(currentRelease, lookin:=xlValues) 'this row gets executed
    releaseFound.Select
End If
© www.soinside.com 2019 - 2024. All rights reserved.