【问题标题】:Index/Match with ListObject (Table)与 ListObject(表)的索引/匹配
【发布时间】:2019-07-12 16:26:23
【问题描述】:

我需要知道某个名称的索引号,例如当我在 TextBox1 = Sara 中写入,然后单击按钮时, 然后 TextBox2 应该返回与表(Table1)中该名称相反的索引值

我在单元格表上尝试了 INDEX/Match 方法,它有效,但我尝试将其转换为 vba 代码,但我得到 msgbox 说

运行时 1004 无法获取 worksheetFunction 类的匹配属性。

我的代码是

Private Sub CommandButton1_Click()
Dim tbl As ListObject
Set tbl = Sheet1.ListObjects("Table1")
TextBox2.Value = Application.WorksheetFunction.Index(Sheet1.tbl.ListColumns(1), Application.WorksheetFunction.Match(TextBox1.Value, tbl.ListColumns(2), 0), 1)
End Sub

我希望TextBox2返回表格上的索引号,如果我在TextBox1上写“Sam”,那么TextBox2应该显示3。

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    如果您使用 WorksheetFunction.Match method 并且没有匹配项,则会引发异常。这可能就是你得到的。

    所以总是这样使用它:

    Dim MatchedRowNumber As Double
    On Error Resume Next 'hide the exception
    MatchedRowNumber = Application.WorksheetFunction.Match(TextBox1.Value, tbl.ListColumns(2), 0)
    On Error Goto 0 'always directly re-activate error reporting!!!
    
    If MatchedRowNumber > 0 Then 'the row number will be 0 if nothing matched
        Dim LookupValue As String
        LookupValue = Application.WorksheetFunction.Index(Sheet1.tbl.ListColumns(1), MatchedRowNumber, 1)
        TextBox2.Value = LookupValue 
    Else
        MsgBox "No match!"
    End If
    

    替代方法是使用Application.Match 函数而不是WorksheetFunction.Match

    Dim MatchedRowNumber As Double
    MatchedRowNumber = Application.Match(TextBox1.Value, tbl.ListColumns(2), 0)
    
    If Not IsError(MatchedRowNumber) Then 
        Dim LookupValue As String
        LookupValue = Application.Index(Sheet1.tbl.ListColumns(1), MatchedRowNumber, 1)
        TextBox2.Value = LookupValue 
    Else
        MsgBox "No match!"
    End If
    

    虽然WorksheetFunction.Match 会引发异常,但Application.Match 会返回一个错误值,您可以使用IsError function 对其进行测试。

    【讨论】:

    • 您可以使用IsError-Function 包装表达式,因此您不必隐藏异常。
    • @MarcoGetrost 不,你不能。 WorksheetFunction.Match 将抛出 IsError 函数无法处理的异常。 • 你可能混淆了WorksheetFunction.MatchApplication.Match(这个返回错误值并且不抛出异常)。
    • @MarcoGetrost 查看更新的答案,现在涵盖了这两种方法。
    猜你喜欢
    • 2018-07-24
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多