1

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

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,因此将不胜感激。re 也是我的范围,并且应该在其中找到许多其他单元格。

谢谢。

编辑:

主要代码和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 先工作,但我仍在苦苦挣扎。

4

1 回答 1

1

问题是您从未将变量“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
于 2013-06-10T14:01:10.997 回答