清除数据时如何避免VLOOKUP Error 1004?

How to avoid VLOOKUP Error 1004 upon clearing data?

我将在 Excel 中开始我的第一个用户表单。

我有一个 ComboBox,它使用下拉列表 select 一个值。一旦这个值被 selected 它使用 VLOOKUP 在文本框中显示其余数据。

使用我在表单上的重置按钮,或尝试取出这些文本框中的数据时,会出现 VLOOKUP 运行时错误,因为数据不再存在。

我该怎么做才能阻止这种情况发生?

Private Sub ComboBox1_Change()
    Dim MyTableArray As Range, MyEmpID As String

    Set MyTableArray = Sheets("CompressorData").Range("A:D")
    Me.txtName.Value = WorksheetFunction.VLookup(Me.ComboBox1, MyTableArray, 2, 0)
    Me.TextBox3.Value = WorksheetFunction.VLookup(Me.ComboBox1, MyTableArray, 1, 0)
    Me.TextBox1.Value = WorksheetFunction.VLookup(Me.ComboBox1, MyTableArray, 4, 0)
End Sub

如果这是您要避免的错误(仅此而已),则在 'On Error' 语句中包含如下内容:

Sub DropDown1_Change()
Dim MyTableArray As Range, MyEmpID As String


    Set MyTableArray = Range("A:D")
    On Error GoTo err_trap
    DropDown1.txtName.Value = WorksheetFunction.VLookup(DropDown1.ComboBox1, MyTableArray, 2, 0)
    DropDown1.TextBox3.Value = WorksheetFunction.VLookup(DropDown1.ComboBox1, MyTableArray, 1, 0)
    DropDown1.TextBox1.Value = WorksheetFunction.VLookup(DropDown1.ComboBox1, MyTableArray, 4, 0)

err_trap:
    MsgBox ("Caught the error - delete msgbox in VB code and replace with 'Exit Sub' to avoid seeing this message box! hardy har captain")
    Exit Sub
    
    
End Sub