Range.Find返回错误对象'_Global'的方法'Range'失败

时间:2018-08-23 13:26:04

标签: excel vba excel-vba runtime-error excel-2010

我正在写一个允许用户输入ID号(QuickRef)的子程序。我正在使用range.find,但是找不到错误“对象'_Global'的方法'范围'失败”的解决方法。

数据集是动态的,因此我建立了一种方法来识别要搜索的正确范围,如下所示:

Dim qRef As String
Dim qCol As Byte
Dim lRow As Long
Dim subject As Range
Dim sRow As Long
Dim found As Range

'Finds the QuickRef column in the dataset
qCol = Cells.Find(What:="QuickRef", _
            After:=Range("DataDump"), _
            LookAt:=xlWhole, _
            LookIn:=xlValues, _
            SearchOrder:=xlByColumns, _
            SearchDirection:=xlNext).Column

'Finds the last row of the dataset
lRow = Cells.Find(What:="*", _
            After:=Range("A1"), _
            LookAt:=xlPart, _
            LookIn:=xlFormulas, _
            SearchOrder:=xlByRows, _
            SearchDirection:=xlPrevious, _
            MatchCase:=False).Row

'Sets the range in which you will search for the QuickRef
Set qRef = Range(Range("DataDump").Offset(1, qCol - 2), Cells(lRow, qCol))

qRef.Select 'confirms the correct range is being referred to.

'error occurs with following line
sRow = Range(qRef).Find(What:=InputBox("Enter main subject QuickRef", "Subject Selection"), _
            After:=Range("A1"), _
            LookAt:=xlWhole, _
            LookIn:=xlValues, _
            SearchOrder:=xlByRows, _
            SearchDirection:=xlNext, _
            MatchCase:=False).Row

debug.print sRow

为什么我会收到此错误?如何克服该错误?

1 个答案:

答案 0 :(得分:2)

这更多是通过其他一些有用的观察结果

1)明确包含要使用的工作表引用,否则隐式使用Activesheet。

2)可能找不到您要查找的内容,然后您将没有.Row可以访问,因为返回的Range对象将为Nothing。对此应该进行测试。

Public Sub GetTotal()
    Dim sRow As Long
    Dim qRef As String
    Dim found As Range

    qRef = "A:A"
    Set found = _
        ThisWorkbook.Worksheets("Sheet1").Range(qRef) & _
        .Find( _
            What:=InputBox("Enter main subject QuickRef", "Subject Selection"), _
            After:=Range("A1"), _
            LookAt:=xlWhole, _
            LookIn:=xlValues, _
            SearchOrder:=xlByRows, _
            SearchDirection:=xlNext, _
            MatchCase:=False)


    If Not found Is Nothing Then
        sRow = found.Row
    End If
    Debug.Print sRow
End Sub