如何查看错过的VLOOKUP键值?

时间:2014-10-30 11:36:20

标签: excel vba excel-vba vlookup

我试图在两列不同的2张纸之间进行VLOOKUP。 以下代码执行vlookup函数并将结果插入到K列中。

我无法管理的事情,如果出现错误(N / A值),如何查看消息框,说明找不到哪些密钥,而不停止vlookup以查找丢失密钥之后的值?如果没有丢失密钥以返回消息框,"所有密钥都存在"。

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

1 个答案:

答案 0 :(得分: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

更新

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