2

我正在寻找仅使用列中唯一文本值填充组合框。如果列中的值是空的(即“”),那么它将从左侧相邻列中获取值(仍然确保它不是重复的)。

我在 Userform 模块中嵌入了一个 Public 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

但是,当我尝试调用 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

任何帮助将非常感激!

长宽

4

1 回答 1

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
于 2012-09-17T01:50:41.350 回答