VLookup的“types不匹配错误”

If first_unit = "N/A" Then我得到一个types不匹配的错误。 我试图根据另一个下拉菜单(B10)中的select更改下拉菜单(B26:C26)的文本。 对于下面的代码:

 Dim check_change As Boolean Private Sub Worksheet_Change(ByVal Target As Range) On Error GoTo 0 If check_change = False Then If Target.Address = Range("B10").Address Then Dim first_unit As Variant Dim second_unit As Variant Dim third_unit As Variant check_change = True first_unit = Application.WorksheetFunction.VLookup(Range("B10:E10"), Sheet3.Range("Jurisdictions_table"), 5, False) second_unit = Application.WorksheetFunction.VLookup(Range("B10:E10"), Sheet3.Range("Jurisdictions_table"), 6, False) third_unit = Application.WorksheetFunction.VLookup(Range("B10:E10"), Sheet3.Range("Jurisdictions_table"), 7, False) Range("D5").Value = first_unit Range("E5").Value = second_unit Range("F5").Value = third_unit If first_unit = "N/A" Then Range("B26:C26").Value = "Certified" End If check_change = False Exit Sub End If If Not Intersect(Target, Range("B19")) Is Nothing Then check_change = True Call ft_to_m(Range("D19"), Range("B19")) check_change = False Exit Sub End If If Not Intersect(Target, Range("D19")) Is Nothing Then check_change = True Call m_to_ft(Range("D19"), Range("B19")) check_change = False Exit Sub End If End If End Sub 

使用Application.VLookup而不是Application.WorksheetFunction.VLookup()以便在查找失败时不会引发错误。 然后,您可以检查IsError()以确定您是否有有效的结果或错误。 在Excel中,如果在查找表中找不到该值,将显示#N / A错误。 使用IsError()会捕获错误。

第一个参数是查找值,而不是范围。 Excel将单元格转换为函数中的值。 所以要清楚你应该使用Range("B10").Value作为第一个参数。 而你不能使用多单元格范围。

 first_unit = Application.VLookup(Range("B10").Value, Sheet3.Range("Jurisdictions_table"), 5, False) second_unit = Application.VLookup(Range("C10").Value, Sheet3.Range("Jurisdictions_table"), 6, False) third_unit = Application.VLookup(Range("D10").Value, Sheet3.Range("Jurisdictions_table"), 7, False) If Not IsError(first_unit) Then Range("D5").Value = first_unit If Not IsError(second_unit) Then Range("E5").Value = second_unit If Not IsError(third_unit) Then Range("F5").Value = third_unit If IsError(first_unit) Then Range("B26:C26").Value = "Certified" End If 

CPearson:error handling与工作表函数

Vlookup中的第一个参数是查找值,而不是范围,我认为它是“B10”而不是范围(“B10:E10”)

你需要使用error handling的Vlookup'启用error handling'错误恢复接下来',而不是错误转到0

 Sub test1() On Error Resume Next first_unit = Application.WorksheetFunction.VLookup(Range("B10").value, Sheet3.Range("Jurisdictions_table"), 5, False) 'first_unit = Application.WorksheetFunction.VLookup(Range("B10:E10"), Sheet3.Range("Jurisdictions_table"), 5, False ) If IsError(first_unit) = False Then ' Example first_unit = "N/A" Else first_unit = "Otherwise" End If End Sub