结果为N / A时Vlookup无法正常工作

时间:2017-03-23 22:18:31

标签: vba excel-vba vlookup excel

我想知道A列中每个值的日期。为此我在VBA上使用VLookup函数,但是当找不到值(= N / A)时代码停止。

我该如何处理这个错误?

这是代码:

Sub lapse_Function()

Dim wsAll As Worksheet
Dim wsDb As Worksheet

Dim lapse As Variant
Dim startDate As Date
Dim Lookup_Range As Range
Dim ID_number As Object

Set wsDb = Worksheets("Database")
Set wsAll = Worksheets("All data")

'Run function
rowNo = 2
Do Until IsEmpty(wsDb.Cells(rowNo, 2))
    'Set values
    studyDate = DateValue("March 3, 2017")

    Set Lookup_Range = wsAll.Range(wsAll.Cells(1, 1), wsAll.Cells(500, 3))
    Set ID_number = wsDb.Cells(rowNo, 2)

    lapse = Application.WorksheetFunction.VLookup(ID_number, Lookup_Range, 3, False) 'Here is where the code stops. I have next the IF in case of error but it won't work
    'Assing value
    If IsError(lapse) Then
        Cells(rowNo, 23).Value = "Less than 4 months" 'NOT WORKING
    Else
        If ((studyDate - lapse) / 7) < 52 Then
            Cells(rowNo, 23).Value = Round(((studyDate - lapse) / 7), 0) & " weeks"
        Else
            Cells(rowNo, 23).Value = Round(((studyDate - lapse) / 360), 1) & " months"
        End If
    End If
    rowNo = rowNo + 1
Loop

End Sub

1 个答案:

答案 0 :(得分:0)

1) - 为了在VLookup之后捕获If IsError(lapse) Then的错误,您需要使用Application.VLookup而不是WorksheetFunction (如@ user3598756所述)。

2) - 稍后您的Cells不完全符合Worksheets,该行: Cells(rowNo, 23).Value = "Less than 4 months"

应该是:

wsDb.Cells(rowNo, 23).Value = "Less than 4 months"

3)而不是使用

If ((studyDate - lapse) / 7) < 52 Then

您可以使用DateDiff函数,第一个参数是"w" - 将间隔说明为周。

  • 首先,它将是:

    If DateDiff("w", lapse, studyDate) < 52 Then

  • 您可以使用的第二个地方

    wsDb.Cells(rowNo, 23).Value = DateDiff("m", lapse, studyDate) & " months"

更新代码

'Run function
rowNo = 2
Do Until IsEmpty(wsDb.Cells(rowNo, 2))
    ' Set values
    studyDate = DateValue("March 3, 2017")
    Set Lookup_Range = wsAll.Range(wsAll.Cells(1, 1), wsAll.Cells(500, 3))
    Set ID_number = wsDb.Cells(rowNo, 2)

    lapse = Application.VLookup(ID_number, Lookup_Range, 3, False)
    ' Assign value
    If IsError(lapse) Then
        wsDb.Cells(rowNo, 23).Value = "Less than 4 months"
    Else
        If DateDiff("w", lapse, studyDate) < 52 Then
            wsDb.Cells(rowNo, 23).Value = DateDiff("w", lapse, studyDate) & " weeks"
        Else
            wsDb.Cells(rowNo, 23).Value = DateDiff("m", lapse, studyDate) & " months"
        End If
    End If
    rowNo = rowNo + 1
Loop