【问题标题】:Dynamic Combo box values动态组合框值
【发布时间】:2014-08-27 05:25:25
【问题描述】:

问题:

我有一个带有 comboBoxtextBoxbutton 的用户表单,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

【问题讨论】:

    标签: vba excel


    【解决方案1】:

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

    为此,请确保在设计模式下将组合框的.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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2012-12-31
      • 2015-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多