2014-10-30 62 views
0

我正在嘗試在2個不同的工作表的2列之間做VLOOKUP。 下面的代碼會執行vlookup函數並將結果插入K列中。如何查看錯過的VLOOKUP鍵值?

我無法管理的事情,如果發生錯誤(N/A值)以查看消息框,說明哪些鍵不是發現,而不會停止查找以下值後缺少密鑰?並且在沒有丟失密鑰的情況下返回消息框,「所有密鑰都存在」。

Sub MissedKeyCheck() 
On Error GoTo MyErrorHandler: 
Dim ws As Worksheet 
Dim LastRow, LastRow1 As Long 
Dim i As String 
Set ws = ActiveWorkbook.Sheets("SheetA") 

LastRow = Sheets("SheetA").Range("B" & Sheets("SheetA").Rows.Count).End(xlUp).Row 
LastRow1 = Sheets("SheetB").Range("C" & Sheets("SheetB").Rows.Count).End(xlUp).Row 

Table1 = Sheets("SheetA").Range("B2:B" & LastRow) 
Table2 = Sheets("SheetB").Range("C3:C" & LastRow1) 

Dept_Row = Sheets("SheetA").Range("K2").Row 
Dept_Clm = Sheets("SheetA").Range("K2").Column 

For Each cl In Table1 
    Sheets("SheetA").Cells(Dept_Row, Dept_Clm) = Application.WorksheetFunction.VLookup(cl, Table2, 1, False) 
    Dept_Row = Dept_Row + 1 
Next cl 

MyErrorHandler: 
If Err.Number = 1004 Then 
    MsgBox "Key: " & " is not present in the SheetB" 
End If 

End Sub 

回答

0

你可以做到這一點,禁用錯誤之前:

On Error Resume Next 
Sheets("SheetA").Cells(Dept_Row, Dept_Clm) = Application.WorksheetFunction.VLookup(cl, Table2, 1, False) 
If Err.Number <> 0 Then 
    ' do something with error 
End If 

' turn error trapping back on 
On Error Goto 0 

UPDATE

Sub MissedKeyCheck() 
On Error GoTo MyErrorHandler: 
Dim ws As Worksheet 
Dim LastRow, LastRow1 As Long 
Dim i As String 
Dim blnError as Boolean 
Dim strMissingKeys as String 
blnError = false 

Set ws = ActiveWorkbook.Sheets("SheetA") 

LastRow = Sheets("SheetA").Range("B" & Sheets("SheetA").Rows.Count).End(xlUp).Row 
LastRow1 = Sheets("SheetB").Range("C" & Sheets("SheetB").Rows.Count).End(xlUp).Row 

Table1 = Sheets("SheetA").Range("B2:B" & LastRow) 
Table2 = Sheets("SheetB").Range("C3:C" & LastRow1) 

Dept_Row = Sheets("SheetA").Range("K2").Row 
Dept_Clm = Sheets("SheetA").Range("K2").Column 

For Each cl In Table1 
    On Error Resume Next 
    Sheets("SheetA").Cells(Dept_Row, Dept_Clm) = Application.WorksheetFunction.VLookup(cl, Table2, 1, False) 
    If Err.Number <> 0 Then 
     ' do something with error 
     blnError=True 
     strMissingKeys = strMissingKeys & cl & "," 
    End If 

    ' turn error trapping back on 
    On Error Goto MyErrorHandler 

    Dept_Row = Dept_Row + 1 
Next cl 

If blnError = True Then 
    MsgBox "Error found in keys: " & vbCrlf & strMissingKeys 
Else 
    MsgBox "No keys missing..." 
End If 



MyErrorHandler: 
If Err.Number = 1004 Then 
    MsgBox "Key: " & " is not present in the SheetB" 
End If 

End Sub 
+0

對不起,我沒有很好地理解在哪裏把這一部分以及如何定義該小區哪裏關鍵不存在 – Ale 2014-10-30 14:08:43

+0

更新示例在回答 – smackenzie 2014-10-30 14:14:21

+0

非常感謝,我現在看到。唯一的問題,當我嘗試運行與F8的代碼,我可以看到,當Err.Number <> 0和'blnError = True'時,它返回cl爲空,並且不返回strMissingKeys值 – Ale 2014-10-30 14:54:04