根据组合框自动更改文本框值

automatically Change txtbox value accourding to combobox

我在工作表 1 的 "A" 列和 "B" 列上有一些员工姓名和员工编号。在用户窗体上,我有一个显示员工姓名的组合框,我希望在组合框上选择姓名时 his/her 员工编号显示在附近的文本框中,我不知道如何。

Me.cboNames
Me.txtEmployeeNumber

可能是这样的(假设您的数据在 sheet "Employee" 中):

Private Sub UserForm_Initialize()

lLastRowEmployee = Worksheets("Employee").Cells(1, 1).End(xlDown).Row 'find las row with data

    For iC = 1 To lLastRowEmployee
        ComboBox1.AddItem Sheets("Employee").Cells(iC, 1) 'load combobox
    Next
End Sub

Private Sub ComboBox1_Change()
    TextBox1 = Worksheets("Employee").Cells(ComboBox1.ListIndex + 1, 2) 'if combo changes, show employee number in texbox1
End Sub

如果您只想显示数字,请考虑使用标签而不是文本框。

下面的代码会将所有值从 Worksheets("Sheet4")(修改为您的 sheet 的名称)加载到 ComboBox(没有循环)。之后,在 Combo-Box Change 事件中,它将修改文本框中的值。

注意:如果您有header行,并且您的数据从第2行开始,请修改以下行:

txtEmployeeNumber.Value = Worksheets("Sheet4").Cells(cboNames.ListIndex + 1, 2)

至:

txtEmployeeNumber.Value = Worksheets("Sheet4").Cells(cboNames.ListIndex + 2, 2)

代码(在User_Form模块内):

Option Explicit

Private Sub cboNames_Change()

txtEmployeeNumber.Value = Worksheets("Sheet4").Cells(cboNames.ListIndex + 1, 2)

End Sub

'============================================ =============================

Private Sub UserForm_Initialize()

Dim LastRow As Long

cboNames.Clear
With Worksheets("Sheet4") '<--replace "Sheet4" with the sheet you have your employees data
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    cboNames.List = Application.Transpose(.Range("A2:A" & LastRow).Value)
End With

End Sub

此代码有效

Private Sub cboName_Change() '<-- your combobox
    Dim EName As String
    Dim Row As Integer
    EName = Me.cboName.Text
    If EName <> "" Then
        With Application.WorksheetFunction
            Row = .Match(EName, Sheets("sheet1").Range("A2:A100"), 0) '< your combobox data worksheet and range 
            txtEmployeeNumber.Text = .Index(Sheets("sheet1").Range("B2:B100"), Row) '< your textbox data worksheet and range

        End With
    End If
End Sub