如何做一个VLookup循环

我尝试search谷歌和提出的代码,但仍不能解决VLookup。

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

我想要做的是,如果AD列中的单元格不为空,则在同一行的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 

你为什么用i ? 它不应该是cell.row ? 如果你使用对象然后使用它,这也会容易得多。 看到这个代码( 未经testing

 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 

像这样的事情应该做的伎俩:

 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