问题
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
回答1:
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.
回答2:
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
回答3:
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
来源:https://stackoverflow.com/questions/42326588/automatically-change-txtbox-value-accourding-to-combobox