【问题标题】:VBA Vlookup always returns #N/AVBA Vlookup 总是返回 #N/A
【发布时间】:2015-09-11 12:55:05
【问题描述】:

我有两个单独的工作簿,其中包含数据。我正在尝试使用 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,这可以正常工作并返回正确的值。要匹配的数据在 Workbook 2 的第 2 列中。

我做错了什么?!?!

【问题讨论】:

  • currVal 定义在哪里?
  • for 循环上方 - 现在已添加整个子例程(见上文)
  • currVal = Cells(currRow, currCol).Value 您应该始终使用特定的工作表参考来限定Cells()。您可能没有得到正确的 currVal
  • 我已经调试并在那里放置了一个断点,它被分配了正确的值!
  • 是您尝试与 UsedRange 中最左边的列匹配的列吗?

标签: excel vba


【解决方案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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 对不起上面已经初始化了,我只是没有包含它。修改了代码。
    • N/A 表示不可用。也许您的一个单元格没有值,因此它不可用。你检查过这个吗?
    • 我不完全理解你的意思...如果我的单元格没有值,将返回 n/a,因为没有匹配...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多