2017-01-09 22 views
3

我使用下面的代碼從excel中的範圍創建一個集合,然後用它來填充用戶窗體上的列表框。代碼在兩個單獨的宏中一直工作正常,但突然都停止工作,並在標題中拋出錯誤。VBA錯誤:此密鑰已與此集合的元素相關聯

Private Sub UserForm_Initialize() 

    Dim ws As Worksheet 
    Dim LR As Long 
    Dim cell As Range 
    Dim List As New Collection 
    Dim Item As Variant 
    Set ws = Worksheets("ExpenseCATs") 

    With ws 
     LR = .Cells(.Rows.Count, 1).End(xlUp).Row 

     For Each cell In .Range("A2:A" & LR) 
      With cell 
       On Error Resume Next 
       List.Add .Text, CStr(.Value) <---------- Error 
       On Error GoTo 0 
      End With 
     Next cell 

     For Each Item In List 
         EXPListBox1.AddItem Item 
     Next Item 

    End With 

由於所有條目的文字,我註釋掉錯誤行的一部分,如下

List.Add .Text ', CStr(.Value) 

這並不會引發錯誤,但列表框不具有唯一值填充,而不是它列出單元格範圍內的所有項目。

我已經看過其他文章在這個錯誤,但無法解決。任何人都可以建議如何解決,也有興趣爲什麼可能停止工作。

回答

3

在VBA項目,選項 - >常規 - >錯誤捕獲,檢查Break On Unhandled Errors

:)

0

我相信將項目添加到收藏當鑰匙被使用過,就會出現此錯誤。 。新增(鍵,值)是相反的順序Dictionary對象

Collection.add(item [,Key]) 
Dictionary.add(Key, item) 

例如:

Dim c As New Collection 
c.add "Value1", Key:="one" 
c.add "Value2", Key:="two" 
c.add "Value3", Key:="one" '<----- this is where the error occurs because of duplicate key 

當然,我無法從你的代碼猜.value,但我以前看過這個錯誤。你確定.Value是獨一無二的嗎?

+0

謝謝,但在我的情況下,這是錯誤捕獲設置如上 –

相關問題