在字典中记数,运行代码时效果不佳,添加检查效果不错

奇怪的问题。 通过检查代码,给我正确的答案。 只是运行它不。

该程序遍历列中的每个单元格,search正则expression式匹配。 当它发现一些东西时,检查一个相邻的列中它属于哪个组,并且保持一个计数。 例如:组3:7,组5:2,组3:8

只是单步执行代码给了我最后的结果不正确,但是添加和检查字典中的每个已知的项目都有诀窍。 每个Dictionary(键)使用Debug.Print来检查每个循环中有多less项目也给我一个很好的输出。

正确//在运行代码之后真正的hamp

  • Group1:23 // Group1:23
  • Group3:21 // Group3:22
  • Group6:2 // Group6:2
  • Group7:3 // Group7:6
  • Group9:8 // Group9:8
  • Group11:1 // Group11:12
  • Group12:2 // Group12:21

    Sub Proce() Dim regEx As New VBScript_RegExp_55.RegExp Dim matches Dim Rango, RangoJulio, RangoAgosto As String Dim DictContador As New Scripting.Dictionary Dim j As Integer Dim conteo As Integer Dim Especialidad As String regEx.Pattern = "cop|col" regEx.Global = False 'True matches all occurances, False matches the first occurance regEx.IgnoreCase = True i = 3 conteo = 1 RangoJulio = "L3:L283" RangoAgosto = "L3:L315" Julio = Excel.ActiveWorkbook.Sheets("Julio") Rango = RangoJulio Julio.Activate For Each celda In Julio.Range(Rango) If regEx.Test(celda.Value) Then Set matches = regEx.Execute(celda.Value) For Each Match In matches j = 13 'column M Especialidad = Julio.Cells(i, j).Value If (Not DictContador.Exists(Especialidad)) Then Call DictContador.Add(Especialidad, conteo) GoTo ContinueLoop End If conteo = DictContador(Especialidad) conteo = CInt(conteo) + 1 DictContador(Especialidad) = conteo Next End If ContinueLoop: i = i + 1 'Debug.Print DictContador(key1) 'Debug.Print DictContador(key2) 'etc Next 'Finally, write the results in another sheet. End Sub 

这就像VBA说:“如果我有机会,我会欺骗你”

谢谢

好像你的主循环可以简化为:

 For Each celda In Julio.Range(Rango) If regEx.Test(celda.Value) Then Especialidad = celda.EntireRow.Cells(13).Value 'make sure the key exists: set initial count=0 If (Not DictContador.Exists(Especialidad)) Then _ DictContador.Add Especialidad, 0 'increment the count DictContador(Especialidad) = DictContador(Especialidad) +1 End If Next 

你会得到不同的结果,通过代码,因为有字典的错误/function,如果你使用手表或立即窗口检查项目将被创build,如果他们不存在。

为了看到这个在variables声明下的第一行放置了一个断点,按F5运行到断点,然后在即时窗口中键入set DictContador = new Dictionary这样字典初始化为空,并为DictContador("a")添加一个监视DictContador("a") 。 您会在当地人窗口中看到"a"作为项目添加。

集合提供了一个没有这个问题的替代方法,它们还显示值而不是键,这对于debugging可能更有用。 另一方面,缺lessExists方法,因此您需要添加on error resume next并testing错误,或者添加一个自定义集合类添加存在的方法。 这两种方法都有权衡。