2016-11-10 99 views
1

我想通過使用for循環和vlookup在vba中將名稱列表與第二個名稱列表進行比較。換句話說,如果一個名字在我的名單和第二個名單上,我想把這個條目標記爲「對手」,將所有其他名稱標記爲「客戶」。vlookup for for lookp with vba

只要列表中的名稱不在第二個列表中,代碼就會產生一個錯誤「運行時錯誤13」,當我想要將該名稱歸類爲客戶端時。

Sub final_row1() 
Dim i As Integer 
    For i = 2 To 10 
     If Cells(i, 2).Value = Application.VLookup(Cells(i, 2), Range("f2:g8"), 1, False) Then 
      Cells(i, 3).Value = "counterparty" 
     Else 
      Cells(i, 3).Value = "client" 
     End If 
    Next i 
End Sub 

回答

0
Sub final_row1() 
Dim i As Integer 
Dim notFound As Boolean 

    For i = 2 To 10 
     notFound = Application.IsError(Application.VLookup(Cells(i, 2), Range("F2:G8"), 1, False)) 
     If notFound = False Then 
      Cells(i, 3).Value = "counterparty" 
     Else 
      Cells(i, 3).Value = "client" 
     End If 
    Next i 
End Sub 
0

嘗試一段代碼下面,我爲了使用Application.VLookup捕獲錯誤。

Sub final_row1() 

    Dim i As Integer 

    For i = 2 To 10  
     ' a match found between both lists  
     If Not IsError(Application.VLookup(Cells(i, 2), Range("F2:G8"), 1, False)) Then 
      Cells(i, 3).Value = "counterparty" 
     Else 
      Cells(i, 3).Value = "client" 
     End If 
    Next i 

End Sub