0

データを含む 2 つの別々のワークブックがあります。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

2 つの列が一致することはわかっていますが、値「#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 に答える