【发布时间】:2020-05-22 04:38:33
【问题描述】:
我需要在具有唯一值的组合框中显示两列 A 和 B。因此,如果两行具有相同的 A 但不同的 B,则它不是重复的,两列都需要重复。我找到了一个代码,其中列出了具有唯一值的一列 (A),但我不知道如何添加列 B。
有一张我的数据的图片以及我想如何在我的 ComboBox 中显示它。
代码如下:
Private Sub UserForm_Initialize()
Dim Cell As Range
Dim col As Variant
Dim Descending As Boolean
Dim Entries As Collection
Dim Items As Variant
Dim index As Long
Dim j As Long
Dim RngBeg As Range
Dim RngEnd As Range
Dim row As Long
Dim Sorted As Boolean
Dim temp As Variant
Dim test As Variant
Dim Wks As Worksheet
Set Wks = ThisWorkbook.Worksheets("Sheet1")
Set RngBeg = Wks.Range("A3")
col = RngBeg.Column
Set RngEnd = Wks.Cells(Rows.Count, col).End(xlUp)
Set Entries = New Collection
ReDim Items(0)
For row = RngBeg.row To RngEnd.row
Set Cell = Wks.Cells(row, col)
On Error Resume Next
test = Entries(Cell.Text)
If Err = 5 Then
Entries.Add index, Cell.Text
Items(index) = Cell.Text
index = index + 1
ReDim Preserve Items(index)
End If
On Error GoTo 0
Next row
index = index - 1
Descending = False
ReDim Preserve Items(index)
Do
Sorted = True
For j = 0 To index - 1
If Descending Xor StrComp(Items(j), Items(j + 1), vbTextCompare) = 1 Then
temp = Items(j + 1)
Items(j + 1) = Items(j)
Items(j) = temp
Sorted = False
End If
Next j
index = index - 1
Loop Until Sorted Or index < 1
ComboBox1.List = Items
End Sub
有什么线索吗?谢谢!
【问题讨论】:
-
你能更好地解释一下“两列都需要重复”是什么意思吗?在同一行上,A 列中的 val 是否足以与 B 不同?
-
我的意思是,除了同一行的条件不同之外,是否有必要每列只包含唯一值?如果之前要进行过滤(为了识别每一列的唯一值,可能会改变同一行上的值之间的对应关系,恐怕......
标签: excel vba combobox multiple-columns unique-values