我终于能够使用与combobox1中的选择相对应的值来加载combobox2。问题是我不能只获得在combobox2中填充的唯一值。它根据combobox1的选择返回所有值,包括重复项。我已将.clear移动到代码中的各个位置,但仅将其从加载多个重复值更改为显示总值1或空白。
以下是我调整代码的来源 https://www.youtube.com/watch?v=yMO_wCZgQbc
(“DATA”)是我的数据所在的工作表 (“CHART”)是我的ComboBox所在的工作表 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
答案 0 :(得分:1)
您需要添加一项检查,看看这些是否已添加到组合框中。 我还在工作表中使用了变量,以便于代码的可读性,并使其更快地输入。
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