dynamiccombobox的值

问题:

我有一个组合文本框button的用户forms,组合的项目是范围内的单元格值( (A1:A10) )。
如果我在comboBox中input一个不在范围内的新文本,我需要将这个值添加到范围,并将其写入文本框 ,如果它已经存在,我想直接写在文本框中
我试图做,但我没有成功。 谁能帮忙?

码:

 Private Sub UserForm_Initialize() 'cmbx.RowSource = "d2:d100" Dim cLoc As Range Dim ws As Worksheet Set ws = Worksheets("LookupLists") For Each cLoc In ws.Range("LocationList") cmbx.AddItem cLoc.Value Next cLoc End Sub 

如果我已经正确地理解了你,那么我猜这就是你想要做的事情?

为此,请确保在devise模式下,将ComboBox的.Style属性设置为0-fmStyleDropDownCombo 。 这将确保您可以inputcombobox。 :)我也评论了代码,这样你就不会有理解代码的问题了。 但如果你仍然这样做,那么只需回发。

我的假设:单元格A10下面没有任何东西

码:

 Dim ws As Worksheet Dim cLoc As Range '~~> Prepare your form Private Sub UserForm_Initialize() Set ws = ThisWorkbook.Sheets("LookupLists") For Each cLoc In ws.Range("LocationList") cmbx.AddItem cLoc.Value Next cLoc End Sub '~~> This will do what you want Private Sub cmbx_AfterUpdate() Dim lRow As Long '~~> Check if the value is in the range '~~> If not then add it to the range and textbox as well If Not IFEXISTS(cmbx.Value) Then lRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row + 1 ws.Range("A" & lRow).Value = cmbx.Value '~~> Delete the Named range so that we can re-create '~~> it to include the new value ThisWorkbook.Names("LocationList").Delete ThisWorkbook.Names.Add Name:="LocationList", RefersToR1C1:= _ "=LookupLists!R1C1:R" & lRow & "C1" End If '~~> Add to textbox TextBox1.Text = cmbx.Value End Sub '~~> function to check if the value is in the textbox or not Function IFEXISTS(cmbVal As String) As Boolean For Each cLoc In ws.Range("LocationList") If UCase(Trim(cLoc.Value)) = UCase(Trim(cmbVal)) Then IFEXISTS = True Exit For End If Next cLoc End Function