2015-11-10 48 views
0

我尝试搜索谷歌和提出的代码,但仍然无法解决VLookup。如何做一个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 
+0

请你在这里上传的完整代码 – Linga

+1

为什么'的IsEmpty(范围( “AD” &I) .Value)= False'?这与你所描述的相反。 – Jeeped

+0

对不起,我在原始描述中省略了“不”,我想要的是如果单元格不为空,则另一个单元格同一行将使用vlookup。谢谢。 – lukayl

回答

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 
+0

是的,它的工作原理!谢谢。 – lukayl

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