2015-09-21 463 views
0

這個'Do While'循環執行,但是vlookup有一個小錯誤。當查找結果爲「NA」時,先前存儲的vLook值被輸入到目的地(單元格(z,20))。我基本上想說iferror(vlookup(...),「」),以便新的存儲值爲零,然後將vLook值更新爲「」並輸入到新的活動單元格中。VLookup在'Do While'循環中

Sub test3() 

Dim text1 As String, text2 As String, text3 As String 
Dim vLook As Variant 
Dim lookupRange As Range 

Set lookupRange = Sheet3.Range("x5:y500") 

Z = 5 

Do While Sheet3.Cells(Z, 1) <> "" 

On Error Resume Next 

text1 = Sheet3.Cells(Z, 23) 

vLook = Application.WorksheetFunction.VLookup(text1, lookupRange, 2, False) 
Sheet3.Cells(Z, 20).Activate 
ActiveCell.Formula = vLook 


Z = Z + 1 
Sheet3.Cells(Z, 24).Select 

Loop 

End Sub 

回答

1

即使你刪除掉WorksheetFunction然後查找不會引發錯誤,如果沒有發現匹配:相反,你可以測試使用IsError()

Sub test3() 

    Dim text1 As String 
    Dim vLook As Variant 
    Dim lookupRange As Range 

    Set lookupRange = Sheet3.Range("x5:y500") 

    Z = 5 

    Do While Sheet3.Cells(Z, 1) <> "" 
     text1 = Sheet3.Cells(Z, 23).Value 
     vLook = Application.VLookup(text1, lookupRange, 2, False) 
     Sheet3.Cells(Z, 20).Value = IIf(IsError(vLook), "N/A", vLook) 
     Z = Z + 1 
    Loop 

End Sub 
+0

完美工作的返回值,我不知道IIF功能存在。萬分感謝。 – KM617