我正在寻找一个只有列中唯一文本值的组合框。如果列中的值为空(即“”),则它将相邻列中的值从左侧开始(仍然确保它不是重复的)。
我在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
非常感谢任何帮助!
LW
答案 0 :(得分: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