Updating unique values in Vlookup

夙愿已清 提交于 2019-12-02 22:08:02

问题


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:


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


来源:https://stackoverflow.com/questions/41658256/updating-unique-values-in-vlookup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!