Updating unique values in Vlookup

2019-03-06 09:54发布

I have the below code, that uses "UG list" as the source and does vlookup on two different sheets - Latency and TT.

If the result is found it passes the string "UG" onto each sheet's specific column.

The problem is even if there are duplicate values the string "UG" gets updated..But what I want is, "UG" should be updated for unique value..it should not be updated for the same value again and again.

Sub vlookup()
Dim cl As Range, Dic As Object
Set Dic = CreateObject("Scripting.Dictionary"): Dic.Comparemode = vbTextCompare
With Sheets("Latency")
For Each cl In .Range("B2:B" & .Cells(Rows.count, "C").End(xlUp).Row)
    If Not Dic.exists(cl.Value) Then Dic.Add cl.Value, cl.Row
Next cl
End With
With Sheets("UG list")
For Each cl In .Range("A2:A" & .Cells(Rows.count, "A").End(xlUp).Row)
    If Dic.exists(cl.Value) Then
        Sheets("Latency").Cells(Dic(cl.Value), 17) = "UG"
    End If
Next cl
End With

With Sheets("TT")
For Each cl In .Range("A2:A" & .Cells(Rows.count, "C").End(xlUp).Row)
    If Not Dic.exists(cl.Value) Then Dic.Add cl.Value, cl.Row
Next cl
End With
With Sheets("UG list")
For Each cl In .Range("A2:A" & .Cells(Rows.count, "A").End(xlUp).Row)
    If Dic.exists(cl.Value) Then
        Sheets("TT").Cells(Dic(cl.Value), 23) = "UG"
    End If
Next cl
End With

Set Dic = Nothing
End Sub

1条回答
Luminary・发光体
2楼-- · 2019-03-06 10:13

Two things:


  1. You are using the same dictionary Dic for different sheets. Before using it for next sheet, clear the dictionary, so that you dont have any old values.

    dic.RemoveAll With Sheets("TT") .........


  1. To prevent the second updates, just remove the item from dictionary, as soon as as you find it first time. Though I am not sure what duplicate value you are referring to, as in dictionary you can't have duplicates.

    If dic.exists(cl.Value) Then
        Sheets("Latency").Cells(dic(cl.Value), 17) = "UG"
        dic.Remove (cl.Value)
    End If
    

If you are just talking about the scenario where if the Column Q already has got "UG" in it and you want to skip that cell then just check it before hand.

  If dic.exists(cl.Value) Then
        If Sheets("Latency").Cells(dic(cl.Value), 17) <> "UG" Then
            Sheets("Latency").Cells(dic(cl.Value), 17) = "UG"
        End If
    End If
查看更多
登录 后发表回答