Excel VBA字典填充异常排查:符合条件的数据无法统计
问题:VBA字典统计去重记录始终返回空值
需要统计某列中满足另外三列同行条件的去重记录数量,使用Scripting.Dictionary实现,但函数始终返回空值,预期字典中应有多条数据。传入的列范围均为无表头的等长区域(最多30000行)。
设置区域代码
Set columnH = Worksheets(sheet).Range("H2:H" & lastRow) 'Department Column Set columnI = Worksheets(sheet).Range("I2:I" & lastRow) 'Item # Column Set columnK = Worksheets(sheet).Range("K2:K" & lastRow) 'CS or PK Column Set columnU = Worksheets(sheet).Range("U2:U" & lastRow) 'UPC Exists Column
调用函数代码
Sheets(pSheet).Range("T4") = ListLength(columnI, columnK, columnH, columnU, "PK-1", "DRY", "Yes") 'Searches for Items that are PK, in DRY department, and have a UPC
函数代码
Function ListLength(Range1, Range2, Range3, Range4, Filter1, Filter2, Filter3) As Long Dim i As Long Dim itemList As Scripting.Dictionary Set itemList = New Scripting.Dictionary i = 0 For Each Item In Range1 If Range2(i) = Filter1 Then If Range3(i) = Filter2 Then If Range4(i) = Filter3 Then If Not itemList.Exists(Item) Then itemList.Add Item.Value, 0 End If End If End If End If i = i + 1 Next Item ListLength = itemList.Count End Function
错误原因排查
- Range对象索引错误:VBA中Range对象的有效索引从1开始,但代码里
i初始化为0,第一次循环时Range2(i)会引用超出范围的Range2(0),导致所有条件判断都不成立,字典无法添加任何条目,最终返回0。 - 字典键类型不匹配:
itemList.Exists(Item)中Item是Range对象,而后续添加的是Item.Value(单元格值),两者类型不同,即使值相同也会被判定为不存在,但这不是当前返回空值的核心原因。
修复后的函数代码
Function ListLength(Range1, Range2, Range3, Range4, Filter1, Filter2, Filter3) As Long Dim i As Long Dim itemList As Scripting.Dictionary Set itemList = New Scripting.Dictionary i = 1 ' 改为从1开始,匹配Range的索引规则 For Each Item In Range1 ' 通过Cells(i)精准定位同行单元格,避免索引越界 If Range2.Cells(i).Value = Filter1 Then If Range3.Cells(i).Value = Filter2 Then If Range4.Cells(i).Value = Filter3 Then ' 统一使用单元格值作为字典键,避免类型不匹配问题 Dim keyVal As Variant keyVal = Item.Value If Not itemList.Exists(keyVal) Then itemList.Add keyVal, 0 End If End If End If End If i = i + 1 Next Item ListLength = itemList.Count End Function
内容的提问来源于stack exchange,提问作者Jerry G
相关产品推荐
相关产品推荐

