2012-06-19 68 views
0

學習一些VBA。到目前爲止,我已經構建這段代碼應該讓我(雖然它沒有,還)做以下的事情:對象變量或變量未設置

  1. 獲取在"M" & i細胞的數量(在第一次迭代是M5 )。
  2. 在A列中找到該號碼。
  3. 一旦找到它,請將PutHereIfFound的值設置爲與F6的值相同(因此爲偏移量)。
  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 
+0

可能有更好的方法來做到這一點。一旦你從'F'得到了值,你想做什麼? –

+0

好吧 - 把它們放到PutHereIfFound中,這是循環第一次迭代中的N5。 – speci

+1

好的,如果我明白你想用Col F值填充COL N,如果找到匹配的話? –

回答

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 
0

在回答你關於Object Variable or With Variable Not Set錯誤的問題,這意味着FindThis沒有被發現和Find返回Nothing

相關問題