'Do While' 循环中的 VLookup
VLookup in 'Do While' loop
这个'Do While'循环执行了,但是vlookup有一个小错误。当 vlookup 结果为 "NA" 时,先前存储的 vLook 值将输入到目的地 (cells(z,20))。我基本上想说 iferror(vlookup(...),"") 以便新存储的值为零,然后将 vLook 值更新为 "" 并在新的活动单元格中输入。
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
如果删除 WorksheetFunction
,则如果未找到匹配项,查找将不会引发错误:相反,您可以使用 IsError()
测试 return 值
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
这个'Do While'循环执行了,但是vlookup有一个小错误。当 vlookup 结果为 "NA" 时,先前存储的 vLook 值将输入到目的地 (cells(z,20))。我基本上想说 iferror(vlookup(...),"") 以便新存储的值为零,然后将 vLook 值更新为 "" 并在新的活动单元格中输入。
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
如果删除 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