VBA Vlookup条件(如果那样)源数据和vlookup范围在不同的工作表上

时间:2014-08-06 01:51:51

标签: vba excel-vba excel

我需要你对条件Vlookup的帮助。我找到了一个代码,如果源数据中有vlookup值,它可以正常运行,但一旦缺少值就会失败。另外我需要添加一个条件('如果查找找到值,则返回“Old”(来自vlookup表中的第二列) '如果找不到值,则返回“New”(只是不是来自vlookup表的文本)。你可以帮帮我吗? 谢谢,'Russ

Sub Vlookup_Condition()
Dim rng As Range
Dim i As Long

With ActiveSheet.Cells
    Set rng = .Range("A1:A" & .Cells(.Rows.count, 1).End(xlUp).row)

    For i = 2 To rng.Rows.count
        'If the value is found by Lookup, then return "Old" (from 2nd column in vlookup table)
        'If the value is NOT found, then return "New" (just text which is not coming from vlookup
        'table)

        rng.Cells(i, 2) = Application.WorksheetFunction.VLookup(.Cells(i, 1), Sheets("Lookuptable").Range("A:B"), 2, False)
    Next
End With

End Sub

2 个答案:

答案 0 :(得分:2)

根据你的谜题。我找到了像Russ这样的解决方案

更新&检测过

Sub Vlookup_Condition() 
Dim rng As Range 
Dim i As Long 

Application.ScreenUpdating = False 

Worksheets("DataFile").Activate 

Range("R2").Activate 

With Worksheets("DataFile").Cells 
Set rng = .Range("O1:O" & .Cells(.Rows.count, 1).End(xlUp).row) 

For i = 2 To rng.Rows.count 

rng.Cells(i, 4) = Application.VLookup(.Cells(i, 15), Sheets("Lookuptable").Range("A:B"), 2, False) 
If IsError(rng.Cells(i, 4)) Then
   If rng.Cells(i, 4) = CVErr(xlErrNA) Then ' Given if condition to change it from "#NA" to "New"
     rng.Cells(i, 4) = "New"
   End If
End If
Next 
End With 

Application.ScreenUpdating = True 

End Sub 

答案 1 :(得分:0)

试试这个

Sub Vlookup_Condition()
Dim rng As Range
Dim ws as Worksheet 
Dim i As Long
Set ws = ActiveSheet
i =2 
With ws.Range("A1:A" & Rows.Count)
    .Formula = "=VLookup(" & ws.Cells(2,1).Address & ",Lookuptable!$A:$B,2,false)"
End With 

Do while ws.Cells(i, 1) <> ""
    if ws.Cells(i,2) <> "OLD" Then ws.Cells(i,2) = "New"
    i = i +1
Loop

希望这有助于有一种更简洁的方法来做到这一点,但这种方式可能更容易建立。

在进一步审核后确定,试试这个!洛尔

With ActiveSheet
        Set rng = .Range("A1:A" & .Cells(.Rows.Count, 1).End(xlUp).Row)

        For i = 2 to rng.Rows.Count
            rng.Cells(i, 2) = Application.WorksheetFunction.VLookup(ActiveSheet.Cells(i,1), Sheets("Lookuptable").Range("A:B"), 2, False)
        Next
    End With
End Sub

我真的希望这适用于你的伴侣如果没有生病可能不会在明天的工作中做任何实际的工作,直到我弄清楚我是如何完全惩罚这个帮助大声笑