在一个循环(为)视觉基础EXCEL中的VLOOKUP

我有以下问题我有一个VLOOKUP,我想在一个循环运行,但是当查找没有find一个相应的值,然后停止脚本。 如果我使用error handling程序来处理错误,那么它将会跳转,并且也会暂停。

Sub Botón1_Haga_clic_en() Dim filas As Integer Dim desdefila As Integer filas = InputBox("Cuantas files tiene éste bloque de pagos?") desdefila = InputBox("Desde que fila empieza?") filasfinal = filas + desdefila For x = desdefila To filasfinal Dim Nombre As String Dim Rango As Range Set Rango = Sheets(6).Range("A:B") Nombre = Application.WorksheetFunction.VLookup(Range("A" & desdefila).Value, Rango, 2, 0) Range("E" & desdefila).Value = Nombre desdefila = desdefila + 1 Next End Sub 

任何想法如何回到循环或处理这个错误?

您可以使用以下结构来处理Vlookup错误:

 Dim myValue As Variant myValue = Application.VLookup("Some Value", Range("A:B"), 2, False) If IsError(myValue) Then 'Code for when not found Else 'Code for when found End If 

请注意,这不使用Application.WorksheetFunction.VLookup ,而是使用Application.VLookup

所以,对于你的代码,error handling将被插入看起来像这样:

 Dim Nombre As Variant Dim Rango As Range Set Rango = Sheets(6).Range("A:B") Nombre = Application.VLookup(Range("A" & desdefila).Value, Rango, 2, 0) If IsError(Nombre) Then 'Code for when not found Else Range("E" & desdefila).Value = Nombre End If desdefila = desdefila + 1 

如果查找失败, WorksheetFunction的早期绑定VLookup函数将引发运行时错误。

如果一个失败的查找是一个特殊的事情 ,你想要处理干净,你需要一个error handling子程序:

  On Error GoTo ErrHandler For ... Nombre = Application.WorksheetFunction.VLookup(Range("A" & desdefila).Value, Rango, 2, 0) '... Next Exit Sub ErrHandler: ' execution jumps here in case of a failed lookup MsgBox "Lookup of '" & Range("A" & desdefila) & "' failed. Please verify data." 'if you want to resume the loop, you can do this: Resume Next 'otherwise execution of the procedure ends here. End Sub 

如果你知道一个失败的查找是一种可能性,但不是非常的例外 ,你只是想处理它,继续前进,你可以使用On Error Resume Next / On Error GoTo 0来隐藏错误:

  On Error Resume Next Nombre = Application.WorksheetFunction.VLookup(Range("A" & desdefila).Value, Rango, 2, 0) If Err.Number <> 0 Then Nombre = "Not Available" Err.Clear On Error GoTo 0 

或者,你可以使用扩展Application接口的延迟版本(如elmer007的答案 ); 而不是在查找失败时引发VBA运行时错误,而是返回一个错误值 ,您可以使用IsError函数进行检查:

 Dim Nombre As Variant 'note "As Variant" For ... Nombre = Application.VLookup(Range("A" & desdefila).Value, Rango, 2, 0) If IsError(Nombre) Then 'handle error value End If '... Next 

使用早期版本的好处之一是,你可以获得参数的智能感知,而你需要确切地知道你在使用后期版本的时候正在做什么。