0

学习一些VBA。到目前为止,我已经构建了这段代码,它应该允许我(虽然它还没有)做以下事情:

  1. 获取"M" & i单元格中的数字(在第一次迭代中是 M5)。
  2. 在 A 列中找到该数字。
  3. 一旦找到它,将值设置PutHereIfFound为与 F6 的值相同(因此偏移)。
  4. 如果找到一个数字,则增加 i 以便循环继续搜索 M6、M7、...,直到单元格 M20。

它返回 a Run-Time Error 91,它代表Object Variable or With Variable not set。当我调试时,它指向该Set PuthereIfFound行。

这个错误的原因是什么?

 Sub FindThis()
    Dim FindThis As Range
    Dim PutHereIfFound As Range
    Dim i As Integer
    Dim f As Integer

    i = 5
    f = 5
    Do
        Set FindThis = ActiveSheet.Range("M" & i)
        Set PutHereIfFound = ActiveSheet.Range("N" & i)
            With ActiveSheet.Range("A:A")
                Set PutHereIfFound = .Find(What:=FindThis, _
                                After:=.Cells(.Cells.Count), _
                                LookIn:=xlValues, _
                                LookAt:=xlWhole, _
                                SearchOrder:=xlByRows, _
                                SearchDirection:=xlNext, _
                                MatchCase:=False).Offset(0, 5)

                If Not PutHereIfFound Is Nothing Then
                    i = i + 1
                Else
                    i = i                       
                End If                                    
            End With
     Loop While i <= 20
End Sub
4

2 回答 2

0

在回答您有关Object Variable or With Variable Not Set错误的问题时,这意味着FindThis未找到并Find返回Nothing.

于 2012-06-19T14:19:42.353 回答
0

根据我的评论,您的代码可以像这样优化。

 Sub FindThis()
    Dim ws As Worksheet
    Dim FindThis As String
    Dim aCell As Range
    Dim i As Long

    Set ws = Sheets("Sheet1")

    With ws
        For i = 5 To 20
            FindThis = .Range("M" & i).Value

            Set aCell = .Columns(1).Find(What:=FindThis, LookIn:=xlValues, _
            LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False, SearchFormat:=False)

            If Not aCell Is Nothing Then
                '~~> Do whatever you want here with the F Value
                PutHereIfFound = aCell.Offset(, 5).Value

                Debug.Print PutHereIfFound
            End If
        Next i
    End With
End Sub
于 2012-06-19T13:27:27.283 回答