Excel VBA Vlookup复制其他工作表中不存在的条目的先前条目数据

时间:2018-03-22 06:02:30

标签: excel vba for-loop error-handling vlookup

我使用以下代码使用vlookup将数据从第一张到第二张。问题是第一张表中没有数据的第二张表条目将填入第二张表的先前条目。有人可以帮我理解我的错误吗?

Dim NIMsLastRow As Integer
Dim NIMsLastCol As Integer
Dim tempInt As Integer
Dim temp3 As String
Dim tempin As String
Dim ColLtr As String
NIMsLastRow = Worksheets("NIMSCarrierCount").Cells(Rows.Count, 1).End(xlUp).Row
NIMsLastCol = Worksheets("NIMSCarrierCount").Cells(1, Columns.Count).End(xlToLeft).Column
AudLastRow = Worksheets("Audit-NIMS vs Site Topology").Cells(Rows.Count, 1).End(xlUp).Row
ColLtr = Replace(Cells(1, NIMsLastCol).Address(True, False), "$1", "")
For i = 2 To NIMsLastCol
    For j = 1 To AudLastRow
        On Error Resume Next
        tempin = Worksheets("Audit-NIMS vs Site Topology").Cells(j, 1).Value
        temp3 = Application.WorksheetFunction.VLookup(tempin, Worksheets("NIMSCarrierCount").Range("A" & 1 & ":" & ColLtr & NIMsLastRow), i, False)
        If IsError(temp3) Then
            Cells(j, i).Value = "NA"
        Else
            Cells(j, i).Value = temp3
        End If
    Next j
Next i

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

Option Explicit

Sub test()

    Dim NIMsLastRow As Long
    Dim NIMsLastCol As Long
    Dim temp3 As Variant 'see change here
    Dim tempin As String
    Dim ColLtr As String
    Dim AudLastRow As Long

    NIMsLastRow = Worksheets("NIMSCarrierCount").Cells(Rows.Count, 1).End(xlUp).Row
    NIMsLastCol = Worksheets("NIMSCarrierCount").Cells(1, Columns.Count).End(xlToLeft).Column
    AudLastRow = Worksheets("Audit-NIMS vs Site Topology").Cells(Rows.Count, 1).End(xlUp).Row
    ColLtr = Replace(Cells(1, NIMsLastCol).Address(True, False), "$1", "")

    Dim j As Long

    For j = 1 To NIMsLastRow

        On Error Resume Next
        tempin = Worksheets("Audit-NIMS vs Site Topology").Cells(j, 1).Value
        temp3 = Application.Match(tempin, Worksheets("NIMSCarrierCount").Range("A1:A" & NIMsLastRow), 0)

        If IsError(temp3) Then

             Cells(j, 2).Resize(1, NIMsLastCol - 1) = "NA"
        Else
             Cells(j, 2).Resize(1, NIMsLastCol - 1).Value = Worksheets("NIMSCarrierCount").Range("B" & temp3 & ":" & ColLtr & temp3).Value
        End If

        On Error GoTo 0

    Next j

End Sub