0

我有两个单独的数据工作簿。我正在尝试使用 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 列中。

我究竟做错了什么?!?!

4

2 回答 2

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
于 2013-01-30T17:25:38.993 回答
0

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

于 2013-01-30T17:28:03.967 回答