2012-09-17 66 views
2

我正在尋找只填充列中唯一文本值的組合框。如果列中的值爲空(即「」),那麼它將來自相鄰列的值向左(仍然確保它不是重複的)。使用唯一值填充Combobox

我已經嵌入用戶窗體模塊內的公用Sub添加的項目,而不重複:

Public Sub addIfUnique(CB As ComboBox, value As String) 

If CB.ListCount = 0 Then GoTo doAdd 
    Dim i As Integer 
    For i = 0 To CB.ListCount - 1 
     If CB.List(i) = value Then Exit Sub 
    Next 
    doAdd: 
     CB.AddItem value 

End Sub 

然而,當我嘗試調用子,它告訴我需要的對象。到目前爲止我所得到的如下:

Worksheets("Scrapers").Activate 
Range("M9").Activate 

Dim intX As Integer 
Dim value As String 

push_lt_cbo.Clear 

Do Until ActiveCell.Offset(0, -1).value = 0 
    If ActiveCell.value = "" Then 
     value = ActiveCell.Offset(0, -1).Text 
     Call addIfUnique((push_lt_cbo), (value)) 
    Else 
     value = ActiveCell.Text 
     Call addIfUnique((CB), (value)) 
    End If 
Loop 

任何幫助將不勝感激!

LW

回答

1

你接近:

Option Explicit 'Add this if you don't already have it 

Private Sub UserForm_Initialize() 
    Worksheets("Scrapers").Activate 
    Range("M9").Activate 

    Dim intX As Integer 
    Dim value As String 

    push_lt_cbo.Clear 


    'Your loop will never end like this: 
    'Do Until ActiveCell.Offset(0, -1).value = 0 

    'Instead use a variable: 
    Dim rowOffset As Integer 
    rowOffset = 0 
    Do Until ActiveCell.Offset(rowOffset, -1).value = 0 
     'There was a lot of extra stuff here. Simplifying: 
     value = ActiveCell.Offset(rowOffset, -1).value 

     'Remove optional CALL keyword. 
     'Also remove paranthesis; they caused the error: 
     addIfUnique push_lt_cbo, value 

     'increment offset: 
     rowOffset = rowOffset + 1 
    Loop 
End Sub 
'Use 'msforms.ComboBox' to clarify. 
Public Sub addIfUnique(CB As msforms.ComboBox, value As String) 

If CB.ListCount = 0 Then GoTo doAdd 
    Dim i As Integer 
    For i = 0 To CB.ListCount - 1 
     If CB.List(i) = value Then Exit Sub 
    Next 
doAdd: 
     CB.AddItem value 

End Sub 
+0

的快速反饋偉大的作品,感謝堆! – Delta