自动更改符合组合框的txtbox值

时间:2017-02-19 11:20:01

标签: excel-vba userform vba excel

我在“A”列上有一些员工姓名,在sheet1中列“B”上有员工编号。在userform上我有一个显示员工姓名的组合框,我想在组合框中选择一个名字,他/她的员工编号显示在附近的txtbox上,我不知道如何。

Me.cboNames
Me.txtEmployeeNumber

3 个答案:

答案 0 :(得分:0)

这样的事情可能(假设您的数据在工作表“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

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

答案 1 :(得分:0)

下面的代码会将ComboBox的所有值加载到Worksheets("Sheet4")(没有循环)(修改为工作表的名称)。之后,在组合框Change事件中,它将修改文本框中的值。

注意:如果您有标题行,并且数据从第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

答案 2 :(得分:0)

此代码有效

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