【问题标题】:Populating a ComboBox with a For loop from the worksheet使用工作表中的 For 循环填充 ComboBox
【发布时间】:2017-06-13 23:23:39
【问题描述】:

在用户在前一个用户表单上选择了工作站后,我试图用部件号列表填充我的用户表单组合框。

我的想法是遍历列,确定字符串何时与工作站匹配,然后将列中的单元格添加到右侧(原来是产品编号)

到目前为止,我的代码如下所示:

If station = "MILL" Then
    With ComboBox1
    .AddItem "350SC109e.1"
    .AddItem "350 SC166"
    .AddItem "350 SC193"
    .AddItem "350 SC195"
    End With
End If

If station = "BRAKE" Then
    For i = 2 To ws1.Range("A265").End(xlUp).Row
    If ws1.Cells(i, 1) = "Brake" Then
       ComboBox1.AddItem ws1.Cells(i, 2)
    End If
    Next i
End If

MILL 是手动执行我想通过 BRAKE if 语句中的循环完成的事情的示例。

【问题讨论】:

  • ComboBox1.AddItem ws1.Cells(i, 2).Value 看起来您正在尝试向组合框添加一个单元格。
  • 那么我需要写什么才能将单元格的值添加到组合框中,而不是单元格本身?
  • 这就是我的猜测。您没有提供有关您的问题的信息。您收到什么错误?
  • 没有错误,当我在第一个用户表单上选择 BRAKE 时,我的组合框是空的。

标签: excel vba combobox userform


【解决方案1】:

在这里,我快速地进行了处理,以证明我可以让它循环工作。不过,您必须进行调整以适应您的需求。它确实完美无缺

Private Sub CommandButton1_Click()

    Dim txtVal As String

    If IsNull(TextBox1.Value) = False Then
        txtVal = TextBox1.Value
    Else
        txtVal = ""
    End If

    Dim rng As Range
    Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1:A21")
    Dim rcell As Range

    For Each rcell In rng.Cells
        If rcell.Value = txtVal Then
            With ComboBox1
                .AddItem rcell.Offset(0, 1).Value
            End With
        End If
    Next rcell

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-23
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多