【发布时间】:2014-11-18 13:27:48
【问题描述】:
我有一段非常简单的代码,它遍历一列数据并向集合添加唯一值。
它是 VBA,所以 Collection 当然缺少 Exists 函数(谁想要那个?),我宁愿避免为列中的每个单元格遍历整个集合,我决定去对于错误处理方法 - 尝试从集合中检索项目,如果它不存在则捕获发生的错误并添加它:
'Trucated the code slightly, I know I should be checking the actual error code, but omitted that for brevity
Dim r As Range
Set r = MySheet.Range("B2") 'First cell in column
Dim uniqueValues As New Collection
Do While r.Value <> ""
On Error GoTo ItemExists
'If r.Value doesn't exist in the collection, throws an error
uniqueValues.Add(Item:=r.Value, Key:=r.Value)
ItemExists:
r.Offset(1)
Loop
问题? Excel 似乎完全忽略了On Error 行,破坏了代码并抛出了Continue/End/Debug 对话框不管。
我检查了 VBA 中的选项,它正确设置为Break on Unhandled Errors.
知道为什么会这样吗?
【问题讨论】:
-
使用
Dictionary而不是Collection -
我在哪里可以找到字典?它似乎不是标准库的一部分。
-
添加对
Microsoft Scripting Runtime或CreateObject("Scirpting.Dictionary")的引用 -
您可能对this attempt at building a better collection 感兴趣。现在可以在Github 上找到整个项目。 (哦,请不要使用
On Error Resume Next,除非您真的了解它的作用。) -
@bp_ 在这种情况下,OERN 绝对没有问题。它可能经常被滥用,但这并不意味着它没有地方! ;)