A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
I created a simple case to illustrate how to do what you want to do, and also to simplify your code a little. The code comes first, then some screen snaps showing the two different ways to look up a student. I only have four TextBoxes, so adjust to your needs.
Eric
'****** BEGIN CODE ******
' This code goes into the code module of the UserForm, and is associated with "CommandButton1",
' which is labeled "Find" in my sample.
Option Explicit
Private Sub CommandButton1_Click()
Dim nRows as Long
Dim theID as Long
Dim theLocker as String
Dim theRow as Long
'
' Must have either Student ID or Locker Number filled in
'
If (TextBox1.Text = "" and TextBox4.Text = "") Then
MsgBox "Dude - you must enter either the Student ID or the Locker Number!", vbOKOnly + vbCritical, "Missing Input"
Exit Sub
End If
'
nRows = ActiveWorkbook.Worksheets("Sheet1").Range("A1").End(xlDown).Row - 1 ' Subtract 1 for header row
'
' Find student with ID or Locker Number:
'
On Error GoTo StudentNotFound
If (TextBox1.Text <> "") Then ' Priority is to search by Student ID
theID = TextBox1.Value
theRow = Application.WorksheetFunction.Match(theID, ActiveWorkbook.Worksheets("Sheet1").Range("$A1:$A" & nRows + 1), 0)
Me.TextBox2.Text = ActiveWorkbook.Worksheets("Sheet1").Range("B" & theRow).Text
Me.TextBox3.Text = ActiveWorkbook.Worksheets("Sheet1").Range("C" & theRow).Text
Me.TextBox4.Text = ActiveWorkbook.Worksheets("Sheet1").Range("D" & theRow).Text
Else ' Search by Locker Number if Student ID is not present
theLocker = TextBox4.Text
theRow = Application.WorksheetFunction.Match(theLocker, ActiveWorkbook.Worksheets("Sheet1").Range("$D1:$D" & nRows + 1), 0)
Me.TextBox1.Text = ActiveWorkbook.Worksheets("Sheet1").Range("A" & theRow).Text
Me.TextBox2.Text = ActiveWorkbook.Worksheets("Sheet1").Range("B" & theRow).Text
Me.TextBox3.Text = ActiveWorkbook.Worksheets("Sheet1").Range("C" & theRow).Text
End If
On Error Goto 0
Exit Sub
'
StudentNotFound:
Me.TextBox2.Text = "Not Found!"
End Sub
Example: Search by Student ID
Example: Search by Locker Number