VBA Vlookup总是返回#N / A.

时间:2013-01-30 17:18:04

标签: excel vba

我有两个单独的工作簿和数据。我正在尝试使用vlookup找到单元格值匹配。

工作簿1中的列包含字母数字数据,与在工作簿2中比较的列一样。

我有以下代码来尝试确定匹配项:

    Sub VirtualHostLookUp()

    'TO DO: iterate through all required workbooks and do lookup

    'open the workbook of interest
    'Workbooks.Open ("C:\Documents and Settings\1147808\My Documents\Pete\Data\tester.xlsx")

    'define this workbook
    Dim campus As Workbook
    Set campus = Workbooks(1)

    'define the lookup range - currently opens the first second open workbook
    Dim rng As range
    If Workbooks.Count > 1 Then
        With Workbooks(2)
            Set rng = .Worksheets(2).UsedRange
        End With
    End If

    'initialise starting point
    Dim currRow, currCol As Integer
    currRow = 3
    currCol = 19

    'get first value to compare
    Dim currVal As Variant
    currVal = Cells(currRow, currCol).Value

    'find the number of rows in the column
    Dim totalRows As Long
    With campus.Worksheets(1)
        totalRows = .Cells(.Rows.Count, "S").End(xlUp).Row
    End With

    campus.Activate

    'iterate through the rows
    For i = currRow To totalRows

        Dim cell As Variant
        Set cell = campus.Worksheets(1).Cells(currRow, currCol + 2)

        If currVal <> Empty Then
            cell.Value = Application.VLookup(currVal, rng, 2, False)

            If Not IsError(cell.Value) Then
                If cell.Value = Empty Then
                    cell.Value = "MATCH"
                End If
            End If
        End If

        'cell.Value = ""

        currRow = currRow + 1
        currVal = Cells(currRow, currCol).Value
    Next 
End Sub

我知道两列之间有匹配,但总是返回值“#N / A”,我无法找出原因?

我已将范围定义为Workbook2中的UsedRange,这可以正常工作并返回正确的值。要匹配的数据位于工作簿2的第2列。

我做错了什么?!?!

2 个答案:

答案 0 :(得分:1)

试试这个:

For i = currRow To totalRows

    Dim cell As Variant
    Set cell = campus.Worksheets(1).Cells(currRow, currCol + 2)

    currVal=cell.Value

    If currVal <> Empty Then
        cell.Value = Application.VLookup(currVal, Workbooks(2).Sheets(2).UsedRange, 2, False)

        If Not IsError(cell.Value) Then
            If cell.Value = Empty Then
                cell.Value = "MATCH"
            End If
        End If
    End If

    currRow = currRow + 1
    currVal = Cells(currRow, currCol).Value
Next

答案 1 :(得分:0)

currVal未初始化,您需要在开始使用之前为其指定正确的值。