Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = Range("G2").Address Then
Update_TextBoxes Range("G2").Value
End If
End Sub
Private Sub TextBox1_Change()
Update_Table_Column Me.TextBox1.Text, "Column2"
End Sub
Private Sub TextBox2_Change()
Update_Table_Column Me.TextBox2.Text, "Notes"
End Sub
Private Sub TextBox3_Change()
Update_Table_Column Me.TextBox3.Text, "Column4"
End Sub
Private Sub TextBox4_Change()
Update_Table_Column Me.TextBox4.Text, "Column5"
End Sub
Private Sub Update_Table_Column(textBoxValue As String, tableColumnName As String)
Dim table As ListObject
Dim customerRow As Variant
'Either: refer to table on the "Table" sheet by its index number
Set table = Worksheets("Table").ListObjects(1)
'Or: refer to table on the "Table" sheet by its name
'Set table = Worksheets("Table").ListObjects("CustomersTable2")
customerRow = Application.Match(Range("G2").Value, table.ListColumns("ID").DataBodyRange, 0)
If Not IsError(customerRow) Then
table.ListColumns(tableColumnName).DataBodyRange(customerRow).Value = textBoxValue
Else
MsgBox "Customer '" & Range("G2").Value & "' not found in table '" & table.Name & "' column 'ID'", vbExclamation
End If
End Sub
Public Sub Update_TextBoxes(CustomerID As String)
Dim table As ListObject
Dim customerRow As Variant
'Either: refer to table on the "Table" sheet by its index number
Set table = Worksheets("Table").ListObjects(1)
'Or: refer to table on the "Table" sheet by its name
'Set table = Worksheets("Table").ListObjects("CustomersTable2")
customerRow = Application.Match(CustomerID, table.ListColumns("ID").DataBodyRange, 0)
If Not IsError(customerRow) Then
'Customrer ID found, so populate each text box with the appropriate table column value
Me.TextBox1.Text = table.ListColumns("Column2").DataBodyRange(customerRow).Value
Me.TextBox2.Text = table.ListColumns("Notes").DataBodyRange(customerRow).Value
Me.TextBox3.Text = table.ListColumns("Column4").DataBodyRange(customerRow).Value
Me.TextBox4.Text = table.ListColumns("Column5").DataBodyRange(customerRow).Value
Else
MsgBox "Customer '" & CustomerID & "' not found in table '" & table.Name & "' column 'ID'", vbExclamation
End If
End Sub