首页 > 解决方案 > 尝试调用名字和姓氏列表但返回不匹配错误

问题描述

我创建了一个表单,它可以从工作表中调用信息,即名字和姓氏。在名称组合框中,当在表单上键入名称时,如果您键入的名称不在列表中,则会出现不匹配的情况。我该如何补救?如果我删除 0 值,则函数不再正确匹配。

* 调用以前的字段 *

Private Sub ComboBox4_Change()

If Me.ComboBox4.Text <> "" Then

 Dim sh As Worksheet
    Set sh = ThisWorkbook.Sheets("Database")
    Dim i As String

  i = Application.Match(Me.ComboBox4.Value, sh.Range("A:A"), 0)


    Me.TextBox2.Value = sh.Range("B" & i).Value

    If sh.Range("H" & i).Value = "Introduced" Then Me.OptionButton1.Value = True
    If sh.Range("H" & i).Value = "Not Introduced" Then Me.OptionButton2.Value = True


    Me.ComboBox1.Value = sh.Range("C" & i).Value
    Me.ComboBox2.Value = sh.Range("D" & i).Value
    Me.ComboBox3.Value = sh.Range("M" & i).Value

    Me.TextBox11.Value = sh.Range("J" & i).Value
     Me.TextBox10.Value = sh.Range("K" & i).Value
       Me.TextBox9.Value = sh.Range("L" & i).Value
     Me.TextBox12.Value = sh.Range("I" & i).Value
  Me.TextBox5.Value = sh.Range("G" & i).Value
    Me.TextBox7.Value = sh.Range("N" & i).Value
End If



End Sub

标签: excelvba

解决方案


有时使用 VBA 的本机函数会使事情变得更容易一些。您可以使用代码Range.Find代替工作表函数Match

Dim sh As Worksheet: Set sh = ThisWorkbook.Sheets("Database")
Dim xName As Range

Set xName = sh.Range("A:A").Find Me.ComboBox4.Value

If xName Is Nothing Then

    'End sub if not found
    MsgBox "Name Not Found - Existing Sub"

Else

    'To access the row use xName.Row
    Me.TextBox2.Value = sh.Range("B" & xName.Row).Value

    '.... rest of code

End If

推荐阅读