如何进行VLookup循环

时间:2015-11-10 10:54:34

标签: excel vba excel-vba

我尝试搜索谷歌和建议的代码,但仍然无法解决VLookup。

我有两个工作簿,一个是ActiveWorkbook,另一个是Template.xls(查找工作表名称" CtyAccesCode"范围A1:B13)。

我想要做的是,如果列AD中的单元格 NOT 为空,则在同一行的AB列中的另一个单元格中使用VLookup来查找对应的。

以下是我使用的内容,但在运行此代码后Excel没有给出值:

For Each cell In Range("H2:H" & LastRow)    ' This is the lookup range
    If IsEmpty(Range("AD" & i).Value) = False Then    ' This finds out if cell in AD is empty
        Cells(i, 28) = Application.WorksheetFunction.VLookup(cell, _
        Workbooks("Template.xls").Worksheets("CtyAccesCode") _
    .Range("A1:B13"), 2, 0)    ' This puts the find out value in cells in column AB or 28
    End If
Next cell  

2 个答案:

答案 0 :(得分:1)

您为什么使用i?不应该是cell.row吗?如果您使用对象然后使用它会更容易。请参阅此代码(未经测试

Sub Sample()
    Dim wbThis As Workbook, wbThat As Workbook
    Dim wsThis As Worksheet, wsThat As Worksheet
    Dim aCell As Range

    Set wbThis = ThisWorkbook
    '~~> Let's say this is the sheet where you want the result
    '~~> Change name as applicable
    Set wsThis = wbThis.Sheets("Sheet1")

    '~~> Change path as applicable
    Set wbThat = Workbooks.Open("C:\Template.xls")
    Set wsThat = wbThat.Sheets("CtyAccesCode")

    With wsThis
        For Each aCell In .Range("H2:H" & LastRow)
            If Len(Trim(.Range("AD" & aCell.Row).Value)) <> 0 Then
                .Cells(aCell.Row, 28) = Application.WorksheetFunction.VLookup( _
                                        aCell.Value, wsThat.Range("A1:B13"), 2, 0)
            End If
        Next aCell
    End With

    wbThat.Close (False)
End Sub

答案 1 :(得分:0)

这样的事情可以解决问题:

For Each cell In Range("H2:H" & LastRow)    ' This is the lookup range
    If IsEmpty(Range("AD" & cell.Row).Value) = False Then    ' This finds out if cell in AD is empty
        Cells(i, 28) = Application.WorksheetFunction.VLookup(Range("AD" & cell.Row), _
                Workbooks("Template.xls").Worksheets("CtyAccesCode") _
                .Range("A1:B13"), 2, 0)    ' This puts the find out value in cells in column AB or 28
    Else
        Cells(i, 28) = Application.WorksheetFunction.VLookup(Range("AB" & cell.Row), _
                Workbooks("Template.xls").Worksheets("CtyAccesCode") _
                .Range("A1:B13"), 2, 0)    ' This puts the find out value in cells in column AB or 28
    End If
Next cell