2016-12-01 75 views
0

所以我想通過名稱和日期列表進行循環。用戶在表單中輸入一個名稱到tb,然後當他們點擊下拉時,它應該填入適用於該名稱的日期。我正在嘗試使用oDictionary方法來說明重複。然而,每次我點擊下拉菜單時,他們都會加倍加註。所以如果他們點擊下拉菜單然後再點擊它,每個日期有兩個值。VBA組合框oDictionary方法重複值

Private Sub cbCancelApptDate_DropButtonClick() 
Dim NamePop As String 
Dim NameRange As Range 
Dim cell As Range 
Dim Countcells As Integer 



NamePop = tbNewApptName.Value 

'Search All Appointments 
    If Sheets("All Appointments").Range("C3") = "" Then 
     Set NameRange = Sheets("All Appointments").Range("C2:C2") 
    Else 
     Set NameRange = Sheets("All Appointments").Range("C2", Sheets("All Appointments").Range("C2").End(xlDown)) 
    End If 


Dim oDictionary As Object 

Set oDictionary = CreateObject("Scripting.Dictionary") 

With Me.cbCancelApptDate 
    For Each cell In NameRange 
     If NamePop = cell.Value Then 
      If oDictionary.exists(cell.Offset(, -2).Value) Then 
       'Do Nothing 
      Else 
       oDictionary.Add cell.Offset(, -2).Value, 0 
       .AddItem cell.Offset(, -2).Value 
      End If 
     End If 
    Next cell 
End With 
+0

在每次點擊時,您都會創建一個新的空字典,因此您將從頭開始重新開始,因此列表會雙倍增加是正常現象。儘量讓你的字典成爲「全球」,也就是說,在任何子字詞之外聲明它。 –

+0

哦拍,好想法。我現在會嘗試。 – SanomaJean

+0

@ A.S.H它工作得非常好,我發佈了Userform初始化的set語句。謝謝! – SanomaJean

回答

1

要使字典跨多次調用(點擊)保存其內容,應將其聲明爲全局。

' outside any sub: 
Dim oDictionary As Object 

'inside the sub: 
if oDictionary Is Nothing Then Set oDictionary = CreateObject("Scripting.Dictionary")