我有:
这个想法是选择一个组合框项目并让另外两个组合框显示同一行中其他单元格中的数据。我有超过5000行数据,并且在所有三列中都有超过一百个空单元格。有些行只有三个单元中的一个或两个包含数据。如果我不包含空单元格,则会遇到组合框中显示错误数据的问题,例如,如果Bar(3,5,10)
为空,则ComboBox1项Foo(11)
将不等于ComboBox2项Bar(11)
,而是显示ComboBox2项目Bar(8)
。
我需要一种方法来隐藏下拉列表中的空组合框项目,但不能从列表中删除它们。
代码作为示例
形式:
Private Sub UserForm_Initialize()
Set FooBar = ActiveWorkbook.Sheets("foobar")
Call PopulateArray(FooBar, 1, Foo)
Call PopulateControl(Foo, UserForm1.ComboBox1)
Call PopulateArray(FooBar, 2, Bar)
Call PopulateControl(Bar, UserForm1.ComboBox2)
Call PopulateArray(FooBar, 2, Baz)
Call PopulateControl(Baz, UserForm1.ComboBox3)
End Sub
Private Sub ComboBox_Change()
ViewSelected UserForm1.ActiveControl
End Sub
模块:
Public Foo(), _
Bar(), _
Baz() As Variant
Public FooBar As Worksheet
Function PopulateArray(Source As Worksheet, Columns as Integer, Target as Variant)
With FooBar
For i = 0 To .UsedRange.Rows.Count - 1
ReDim Preserve Target(i): Target(i) = Cells(i + 1, Column)
Next i
End With
End Function
Function PopulateControl(Source As Variant, Target As Control)
For i = 0 To UBound(Source)
Target.AddItem Source(i)
Next i
End Function
Function ViewSelected(Selected As control)
Dim i As Integer: i = Selected.ListIndex
For Each control in UserForm1.Controls
If TypeName(control) = "ComboBox" Then control.ListIndex = i
Next control
End Function
数据示例
Column 1 Column 2 Column 3
Foo1 Bar1 Baz1
Foo1 Bar1 Baz2
Foo1 Bar2 Baz3
Foo1 Bar2 Baz4
Foo2 Bar11 Baz11
Foo2 Baz12 'missing Bar11
Foo2 Bar12 Baz13
Foo2 Bar12 'missing Baz14
答案 0 :(得分:1)
给定一列的索引(选定的值),您希望找出与原始列中的空白数相对应的其他列的相应索引。
因此,我们在(在此示例中)查找相应数组Foo
:
Dim i As Integer
Dim j as Integer
For i = 0 to Selected.ListIndex
if Foo(i) = "" Then j = j + 1
j = j + 1
Next i
我们只计算了所选值之前的空白数量。
现在您知道用户选择的列的原始索引(包括空白)。最后,我们在每个(其他)控件中查找相应的值,此处源自Bar
和Baz
:
UserForm1.ComboBox1.Text = Bar(j)
Userform1.ComboBox2.Text = Baz(j)