VBA .findnext无效。运行时错误91对象变量或未设置块变量

时间:2013-06-10 12:38:08

标签: vba find range runtime-error with-statement

我正在尝试执行搜索,在列中搜索“REQM”(无引号)并将找到的单元格的范围设置为d。然后调用另一个子函数,查找输入数据的位置。我的FindEntryArea子函数工作正常,我的第一个查找工作得很好,但是当它试图找到它时,它无法正常工作。

Sub FindLoop()
Dim re as Range
Set re = Sheets(1).Range("T:T")

With re
    Set d = .Find("REQM", LookIn:=xlFormulas, LookAt:=xlWhole)
    MsgBox (d.Row)
    Call FindEntryArea
    Do
        Set d = .FindNext(d)
        MsgBox (d.Row)
        Call FindEntryArea
    Loop While Not d Is Nothing
End With


End Sub

试图找出错误我用msgbox打印出正在发现的范围的行,这对第一个单元格工作正常,但不适用于findnext。我得到对象变量或没有设置块变量。我是VBA的新手,这是我第一次使用findnext,所以任何指导都将不胜感激。另外还有我的范围,其中还有很多其他细胞。

感谢。

编辑:

主要代码和findloop

Public re As Range
Public d As variant
Sub MainCode()

Dim r as Range
Set re = Worksheets("Summary all PIIDB").Range("T:T")

Set r = Worksheets("Summary all PIIDB")
With r
    Call FindLoop
End With
End Sub

Sub FindLoop()

With re
    Set d = .Find("REQM", LookIn:=xlFormulas, LookAt:=xlWhole)
    MsgBox (d.Row)
    'Call FindEntryArea
        Set d = .FindNext(d)
        MsgBox (d.Row)
        'Call FindEntryArea
End With


End Sub

我删除了循环只是为了让findnext先工作但我还在努力。

1 个答案:

答案 0 :(得分:0)

问题是你永远不会将变量“re”或“c”设置为任何东西。在使用它们之前,您确实应该声明所有变量,以帮助减少错误。尝试这样的事情:

Sub FindLoop()
    Dim prevSheet as Worksheet
    Dim rng As Range
    Dim fnd As Variant
    Dim i As Long

    prevSheet = ActiveSheet
    Sheets(1).Select

    'Column T - UsedRange
    Set rng = Sheets(1).Range(Cells(1, 20), Cells(ActiveSheet.UsedRange.Rows.Count, 20))

    On Error GoTo Not_Found
    i = rng.Find("REQM", LookIn:=xlFormulas, LookAt:=xlWhole).Row
    On Error GoTo 0

    With rng
        Set fnd = .Find("REQM", LookIn:=xlFormulas, LookAt:=xlWhole)
        Do
            Set fnd = .FindNext(fnd)
            Call FindEntryArea
            MsgBox (fnd.Row)
        Loop While i < fnd.Row
    End With
    prevSheet .select

    Exit Sub

Not_Found:
    MsgBox """REQM"" not found."
    prevSheet.Select
    Exit Sub
End Sub

编辑: 我修改了你发布的代码,它正确地为我运行。

Option Explicit
Public d As Variant
Public re As Range

Sub MainCode()

    Dim r As Range
    Set re = Worksheets("Summary all PIIDB").Range("T:T")

    Set r = Worksheets("Summary all PIIDB").UsedRange
    With r
        Call FindLoop
    End With
End Sub

Sub FindLoop()
    On Error GoTo Not_Found
    With re
        Set d = .Find("REQM", LookIn:=xlFormulas, LookAt:=xlWhole)
        MsgBox (d.row)
        'Call FindEntryArea
        Set d = .FindNext(d)
        MsgBox (d.row)
        'Call FindEntryArea
    End With
    On Error GoTo 0
    Exit Sub

Not_Found:
    MsgBox ("REQM not found!")
    Exit Sub
End Sub