Excel '13 VBA 级联 ComboBox - 无法在 Combobox2 中获取唯一值

Excel '13 VBA Cascading ComboBox - Trouble getting unique values in Combobox2

我终于能够让 combobox2 加载与在 combobox1 中所做的选择相对应的值。问题是我不能只获取唯一值来填充 combobox2。它 returns 基于 combobox1 的选择的所有值,包括重复值。我已将 .clear 移动到代码中的各个位置,但这只会将其从加载多个重复值更改为显示 1 个总值或空白。

这是我改编代码的来源 https://www.youtube.com/watch?v=yMO_wCZgQbc

("DATA") 是我的数据所在的工作表 ("CHART") 是我的组合框所在的工作表 cmbRent = ComboBox1 cmbSub = ComboBox2

    Private Sub cmbRent_Change()

MyVal = Me.cmbRent.Value

'loop thru col B
lr = ThisWorkbook.Sheets("DATA").Cells(Rows.Count, 1).End(xlUp).Row

  'clear cmbSub
    ThisWorkbook.Sheets("CHART").cmbSub.Clear


'loop thru
For x = 2 To lr
    If MyVal = ThisWorkbook.Sheets("DATA").Cells(x, 1) Then
        'add to combobox
   ThisWorkbook.Sheets("CHART").cmbSub.AddItem ThisWorkbook.Sheets("DATA").Cells(x, 2)
  End If

Next x


      ThisWorkbook.Sheets("CHART").cmbSub.ListIndex = -1
End Sub

您需要添加一个检查以查看这些是否已添加到组合框中。 我还为工作表使用了变量,以方便代码的可读性并加快输入速度。

Dim wsChart As Worksheet
Dim wsData As Worksheet
Dim listOfValues As String 'To store list of values already added
Dim ValueToAdd As String 'To store new value to add
listOfValues = ""
Set wsChart = ThisWorkbook.Sheets("CHART") 
Set wsData = ThisWOrkbook.Sheets("DATA")

.....(insert rest of code here)

For x = 2 To lr
    If MyVal = wsData.Cells(x, 1) Then
       'add to combobox
        ValueToAdd = wsData.Cells(x,2) 'Get value from worksheet
        If InStr(listOfValues, valueToAdd) = 0 Then
        'Check to see if the value has already been added
        'If not, add to values added and add the item to the combobox.
              listOfValues = listOfValues & ValueToAdd
              wsChart.cmbSub.AddItem valueToAdd
        End If
    End If
Next x