Range.FindNext导致运行时错误91

时间:2018-02-01 23:54:21

标签: excel vba excel-vba loops

我正在使用VBA在15x15数组中搜索所有' 1的位置(行号和列号)并将它们映射到新位置。

Sub findvalues()
Dim OldRow As Long
Dim OldColumn As Long

With Worksheets(1).Range("a1:o15")
    Set c = .Find(1, LookIn:=xlValues)
    If Not c Is Nothing Then
        firstAddress = c.Address
        Do
            cellAddress = c.Address
            OldRow = Range(cellAddress).Row
            OldCol = Range(cellAddress).Column
            MsgBox (OldRow)

            With Worksheets(1).Range("r3:r16")
                Set oldmapping = .Find(OldRow, LookIn:=xlValues, LookAt:=xlWhole)
                NewCol = oldmapping.Offset(, 1).Value
                MsgBox (NewCol)
            End With

            Set c = .FindNext(c)
            MsgBox (c.Address)
        Loop While Not c Is Nothing And c.Address <> firstAddress
    End If
End With

End Sub

奇怪的是,代码运行正常,直到第四个循环到达MsgBox (c.Address)并抛出

  

运行时错误91 - 未设置对象变量

我感觉它已经下降到前一行的Set c = .FindNext(c),但无法找出原因,因为它适用于前3个循环。

2 个答案:

答案 0 :(得分:2)

.FindNext派生自,

Set c = .Find(1, LookIn:=xlValues)

......正被中间人取代,

Set oldmapping = .Find(OldRow, LookIn:=xlValues, LookAt:=xlWhole)

您的.FindNext和循环条件不再有效。

切换到第二种方法的替代方法。

Option Explicit

Sub findvalues()
    Dim OldRow As Long, OldCol As Long, NewCol As Long
    Dim oldmapping As Variant, c As Range, firstAddress As String, cellAddress As String

    With Worksheets(1).Range("a1:o15")
        Set c = .Find(1, LookIn:=xlValues)
        If Not c Is Nothing Then
            firstAddress = c.Address
            Do
                cellAddress = c.Address
                OldRow = Range(cellAddress).Row
                OldCol = Range(cellAddress).Column
                MsgBox (OldRow)

                oldmapping = Application.Match(OldRow, Worksheets(1).Range("r3:r16"), 0)
                If Not IsError(oldmapping) Then
                    NewCol = Worksheets(1).Range("r3:r16").Cells(oldmapping).Offset(, 1).Value
                    MsgBox NewCol
                End If

                Set c = .FindNext(c)
                MsgBox (c.Address)
            Loop While Not c Is Nothing And c.Address <> firstAddress
        End If
    End With

End Sub

答案 1 :(得分:0)

当测试为真时,while(或while)循环仍将运行一次,这是一个简单的例子:

Sub temp()
Dim X As Long
X = 0
Do
    X = X + 1
    Debug.Print X
Loop While X < 5
End Sub

注意5显示在调试窗口的值列表中。

一个简单的测试应该为你解决这个问题。

If Not c Is Nothing then MsgBox (c.Address)

或者你可以告诉它退出循环如果c什么都没有,你的选择