拆分为数组并使用独特的填充组合框

时间:2014-05-21 11:27:21

标签: arrays excel vba excel-vba

我有动态

range("A1:ZZ1")

在此范围内,每个单元格用逗号分隔值

cell("A1")= "City, street, Nr" and etc...

我有两个组合框 In first, i must select from all cities in range, show only Cities name

for each cell in range("A1:ZZ1")
  CitiesArr(x) = split(cell.value,",")
  x=x+1
next cell
me.combobox1.list CitiesArr(1,1) ???

In second, i must depending on first selected city, select from all selected cities in range

If me.combobox1.value="Moscow" then me.combobox2.list = CitiesArr(which contains "Moscow")

我混淆了怎么做((

So if 
cell("A1") ="Moscow, Lenin str.,12"
cell("B1") ="Moscow, Centralnaja str.,1"
cell("C1") ="Moscow, Lenin str.,98"
cell("D1") ="Krim, Chingis str.,23"
cell("F1") ="Krim, MUrashev str.,45"
....
cell("ZZ1") ="Belostok, Kazik str.,6"

in combobox1 I must have UNIQUE (sort Desc)

Moscow
Krim
....
Belostok

If I select in combobox1 field Moscow then in combobox2 i must see (sort Desc by Street column)

Moscow, Lenin str.,12
Moscow, Centralnaja str.,1
Moscow, Lenin str.,98
....

1 个答案:

答案 0 :(得分:1)

这是你在尝试的吗?

我在5个单元格中采集了样本数据进行演示。请根据需要更改代码。

Option Explicit

Dim aCell As Range

Private Sub UserForm_Initialize()
    '~~> Change Sheet1 to the relevant sheet name
    '~~> Change A1:E1 to the relevant range
    For Each aCell In ThisWorkbook.Sheets("Sheet1").Range("A1:E1")
        If InStr(1, aCell.Value, ",") Then _
        ComboBox1.AddItem Split(aCell.Value, ",")(0)
    Next aCell

    '~~> Remove duplicates
    RemoveDuplicates ComboBox1
End Sub

Private Sub ComboBox1_Click()
    Dim tmpStr As String

    ComboBox2.Clear

    For Each aCell In ThisWorkbook.Sheets("Sheet1").Range("A1:E1")
        If InStr(1, aCell.Value, ",") Then _
        tmpStr = Split(aCell.Value, ",")(0)

        If Trim(ComboBox1.Value) = Trim(tmpStr) Then _
        ComboBox2.AddItem aCell.Value
    Next aCell
End Sub

'~~> Procedure to remove duplicates
Private Sub RemoveDuplicates(cmb As ComboBox)
    Dim a As Integer, b As Integer, c As Integer

    a = cmb.ListCount - 1
    Do While a >= 0
        For b = a - 1 To 0 Step -1
            If cmb.List(b) = cmb.List(a) Then
                cmb.RemoveItem b
                a = a - 1
            End If
        Next b
        a = a - 1
    Loop
End Sub

enter image description here