循环中的VLOOKUP(FOR)VISUAL BASIC EXCEL

时间:2017-01-13 16:25:47

标签: excel vba excel-vba for-loop vlookup

我有以下问题 我有一个VLOOKUP,我想在循环中运行,但是当vlookup找不到相应的值时,它会暂停脚本。如果我使用错误处理程序处理错误,它将跳转并且还会暂停它。

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

有关如何返回循环或处理此错误的任何想法?

2 个答案:

答案 0 :(得分:3)

您可以使用以下结构处理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

因此,对于您的代码,将插入错误处理,如下所示:

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

答案 1 :(得分:1)

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

如果失败的查找是特殊事物并且您想要干净地处理它,则需要一个错误处理子例程:

    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's answer中所示);当查找失败时,它不会引发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

使用早期版本的一个优点是,您可以获得参数的IntelliSense,而您需要确切知道在使用后期版本时您正在做什么。

相关问题