0

いくつかのVBAを学ぶ。これまでのところ、私は次のことを実行できるようにする必要があるこのコードを作成しました(まだ実行していませんが)。

  1. セル内の番号を取得し"M" & iます(最初の反復ではM5です)。
  2. A列でその番号を見つけます。
  3. 見つかったら、PutHereIfFoundF6の値と同じ値を設定します(したがって、オフセット)。
  4. 数値が見つかった場合は、iをインクリメントして、ループがM6、M7、...すべてをセルM20まで検索し続けるようにします。

を返す、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 に答える