我正在使用带有多个列的ComboBox,第一个被隐藏,但绑定到ComboBox的Value,所以Combobox1.Value
将返回所选行的第一列的值,而显示的值将是第二列中的值。
获取ComboBox的选定值不是问题,但是设置行就可以了。看来您无法使用ComboBox1.Value = ...
选择ComboBox行(请参阅this question以作参考),也不能使用ComboBox1.Text = ...
,因为Text
链接到第二列,而不是链接到第二列。首先。
由于第一列的值没有排序,并且某些值可能会丢失,所以我不能使用直接的ComboBox1.ListIndex = ...
来选择一行。
我的猜测是,我将不得不使用For ...
循环来解析第一列来设置值,但是也许有更简单的方法吗?
下面是我用于测试的代码,将ComboBox和TextBox放在UserForm上并粘贴代码以进行尝试。
Option Explicit
Private Sub ComboBox1_Change()
'TextBox1 = ComboBox1.Value 'Getting the Value is easy
End Sub
Private Sub TextBox1_Change()
On Error GoTo Error_
ComboBox1.Value = CLng(TextBox1) 'Not working, cannot set ComboBox's Value property
ComboBox1.Text = CLng(TextBox1) 'Not working, Text property is second column, so the values is invalid
Debug.Print TypeName(ComboBox1.Value) 'First column seems to be type Double, so try with CDbl instead of CLng
ComboBox1.Value = CLng(TextBox1) 'Not working, cannot set ComboBox's Value property
ComboBox1.Text = CLng(TextBox1) 'Not working, Text property is second column, so the valie is invalid
Dim i As Long
For i = 0 To ComboBox1.ListCount - 1
If ComboBox1.List(i, 0) = CLng(TextBox1) Then ComboBox1.ListIndex = i
Next i
Exit Sub
Error_:
Debug.Print Err.Number, Err.Description
Resume Next
End Sub
Private Sub UserForm_Initialize()
ComboBox1.ColumnCount = 2 '2 columns
ComboBox1.BoundColumn = 1 'Value is linked to 1st column
ComboBox1.ColumnWidths = "0 pt" 'Hide 1st column
ComboBox1.Style = fmStyleDropDownList 'List style
ComboBox1.MatchRequired = True 'Match required
ComboBox1.List = [{1,"Choice 1";2,"Choice 2";4,"Choice 4"}] 'List values
End Sub