2015-11-10 89 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