automatically Change txtbox value accourding to co

2019-09-08 17:53发布

I have some employee Names on column "A" and employee Numbers on column "B" in sheet1. On userform I have a combobox that shows employee names,i want when a name is selected on combobox his/her employee Number shown on a nearby txtbox and i dont know how.

Me.cboNames
Me.txtEmployeeNumber

3条回答
相关推荐>>
2楼-- · 2019-09-08 18:12

Something like this maybe (assuming your data is in 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

If you like just to show the number, consider using a label instead of a textbox.

查看更多
我想做一个坏孩纸
3楼-- · 2019-09-08 18:26

The code below will load all values to the ComboBox (without a loop) from Worksheets("Sheet4") (modify to your sheet's name). Afterwards, on the Combo-Box Change event it will modify the value in the text box.

Note: If you have a header row, and you data starts from the 2nd row, modify the line below :

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

to:

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

Code (inside the User_Form module):

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
查看更多
别忘想泡老子
4楼-- · 2019-09-08 18:28

This code works

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
查看更多
登录 后发表回答