对于这个简单的示例,我将您的工作表与产品一起称为“产品”。有两列,A 列中的名称和 B 列中的 ID
在用户窗体上,我放置了两个名为
文本框_产品名称
TextBox_ProductID
然后,我将以下代码添加到 Userform 中,只要产品名称文本框的值发生更改并且失去焦点,就会触发该代码。
Private Sub TextBox_Productname_Change()
' Clear the content of all Textboxes but the Productname
TextBox_ProductID.Value = ""
' Analyse the Cells in the Worksheet called "Products"
With Worksheets("Products")
' Assume in the first row are the headers so start
' looking at the second row and go to the final one
For i = 2 To .UsedRange.Rows.Count
' check whether the value in the first column
' matches the value of the Textbox_Productname
If .Cells(i, 1) = TextBox_Productname.Value Then
' If there is a match copy the values of all
' the other columns to the textboxes
TextBox_ProductID.Value = .Cells(i, 2)
End If
Next i
End With
End Sub