使用Dic在VBA中查找匹配和更新列

我试图用Dictionary来完成下面的任务:(不要问为什么:P,我刚刚find了这个方法,并开始使用它,并没有注意其他的可能性,欢迎任何更好的方法)

  • 在表格“DRG”中检查栏AE中的字母“TRUE”。

  • 如果find了,那么将表格“DRG”的列E中的值与表格“延迟”的列表R中的值进行比较。

  • 如果在“延迟”表中find匹配项,并且在工作表DRG中的值为“TRUE”,则更新“延迟”表中ColS中的文本“IP”。

我有下面的代码,并不知道在哪里包括比较工作表“Latency”的Col R和表“DRG”

我的代码

 Sub IPFinder() Dim cl As Range, Dic As Object Set Dic = CreateObject("Scripting.Dictionary"): Dic.Comparemode = vbTextCompare With Sheets("Latency") For Each cl In .Range("R2:R" & .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("DRG") For Each cl In .Range("AE2:AE" & .Cells(Rows.Count, "A").End(xlUp).Row) If Dic.exists(cl.Value) = "TRUE" Then Sheets("Latency").Cells(Dic(cl.Value), 19) = "IP" End If If Dic.exists(cl.Value) Then Sheets("Latency").Cells(Dic(cl.Value), 19) = "IP" Dic.Remove (cl.Value) End If Next cl End With Set Dic = Nothing End Sub 

遵循你的描述:

  • 在表格“DRG”中检查栏AE中的字母“TRUE”。

  • 如果find了,那么将表格“DRG”的列E中的值与表格“延迟”的列表R中的值进行比较。

  • 如果在“延迟”表中find匹配项,并且在工作表DRG中的值为“TRUE”,则更新“延迟”表中ColS中的文本“IP”。

代码应该如下调整(见注释):

 Option Explicit Sub IPFinder() Dim cl As Range, Dic As Object Set Dic = CreateObject("Scripting.Dictionary"): Dic.Comparemode = vbTextCompare With Sheets("Latency") For Each cl In .Range("R2:R" & .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("DRG") With .Range("AE1:AE" & .Cells(Rows.Count, "A").End(xlUp).Row) '<--| reference its column AE range from row 1 (header) down to the one corresponding to last column A not empty row .AutoFilter Field:=1, Criteria1:="TRUE" '<--| filter column AE cells with "TRUE" content If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then '<--| if any cell found For Each cl In .Resize(.Rows.Count - 1).Offset(1, -26).SpecialCells(xlCellTypeVisible) '<--| loop through column "E" cells correesponding to filtered ones in column "AE" (skipping headers) If Dic.exists(cl.Value) Then Sheets("Latency").Cells(Dic(cl.Value), "S") = "IP" '<--| if cirrent column E cell value matches any "Latency" sheet column R one then write "IP" in "Latency" sheet corresponding column S cell Next End If End With .AutoFilterMode = False End With Set Dic = Nothing End Sub