使用工作表中的 For 循环填充 ComboBox

Populating a ComboBox with a For loop from the worksheet

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

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

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

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 语句中的循环完成的事情的示例。

在这里,我快速地完成了这个,以证明我可以让它在一个循环中工作。不过,您必须进行调整以满足您的需求。它确实完美地工作

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