VBA词典不添加值

我试图编写一个函数来search某个列(称为列A)的术语“请求”。 一旦find该行,它将search同一行中的另一列(称为列B)以获取唯一的字词。 我们的目标是计算B列中有多less独特的术语与A列中的术语“请求”相对应。我试图做到这一点的方法是创build一个字典并添加一个术语,如果该术语尚不存在在字典里。 该程序计算了词典中添加了多less条款,因此我知道有多less条特殊条款。 然而,我现在的代码只是不断地在词典中添加每一个词,而不pipe该词是否已经存在或不存在。 我一直在试图找出一段时间,不能完全弄清楚。 代码如下:

j = 0 For i = 1 To LastRow If Cells(i, 13).Value Like "Request" Then Set dic = CreateObject("Scripting.Dictionary") If Not dic.exists(Cells(i, 13)) Then ucount = ucount + 1 dic.Add j, Cells(i, 13) j = j + 1 End If End If Next i 

我认为这个问题可能与dic.Addfunction有关,但我不确定。 我对VBA和一般编码都比较陌生。

 Dim dict as Object, tmp Set dict = CreateObject("Scripting.Dictionary") For i = 1 To LastRow If Cells(i, "A").Value = "Request" Then tmp = Cells(i, "B").Value If Not dict.exists(tmp) Then dict.Add tmp, 1 End If End If Next i Debug.Print dict.Count 'no need for a separate counter 

你的问题是这条线是:

  Set dic = CreateObject("Scripting.Dictionary") 

每次你点击这一行,你的字典就会重置并重新初始化。

在整个循环之前移动它:

  j = 0 Set dic = CreateObject("Scripting.Dictionary") For i = 1 To LastRow If Cells(i, 13).Value Like "Request" Then If Not dic.exists(Cells(i, 13).value) Then ucount = ucount + 1 dic.Add j, Cells(i, 13).value j = j + 1 End If End If Next i