动态组合框值

时间:2014-08-27 05:25:25

标签: excel vba excel-vba

问题:

我有一个带有 comboBox textBox 按钮的用户表单, comboBox 的项目是单元格值的范围(例如(A1:A10)) 如果我在 comboBox 中输入不在范围内的新文本,我需要将此值添加到范围中,并将其写入 textBox ,如果是已存在我想直接在 textBox 中编写它 我试着这样做,但我没有成功。 有人可以帮忙吗?

代码:

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

1 个答案:

答案 0 :(得分:1)

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

为此,请确保在设计模式下,将ComboBoxes的.Style属性设置为0-fmStyleDropDownCombo。这将确保您可以输入组合框。 :)我还评论了代码,以便您在理解代码时不会遇到任何问题。但如果你仍然这样做,那么只需回复。

我的假设:单元格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