首页 > 解决方案 > VBA 错误处理(Excel 中的索引/匹配)

问题描述

在 Excel 中,可以使用 INDEX 和 MATCH 函数从范围中查找值;

在此处输入图像描述

通常使用以下表达式:

=INDEX(tablerange,MATCH(rowval,col1range,0),MATCH(colval,row1range,0))

但是,由于我经常需要此功能,因此我创建了自己的简单自定义 VBA 函数,该函数TabVal()根据标题列/行的给定值从给定范围返回一个值:

Public Function TabVal(t As Range, r As Range, c As Range)
Dim x, y As Integer
On Error GoTo ERROR
    x = Application.WorksheetFunction.Match(r.Cells(1, 1).Value, t.Columns(1), 0)
    y = Application.WorksheetFunction.Match(c.Cells(1, 1).Value, t.Rows(1), 0)
    TabVal = t.Cells(x, y).Value
    Exit Function
ERROR:
    TabVal = ""
End Function

这对其他人可能有用。但是在 VBA 中是否有更好的错误处理方法而不是GoTo ERROR(标签)?

标签: excelvbaexceptionexcel-formulaoffice365

解决方案


如评论中所述,使用Application.Matchand的方法IsError

Public Function TabVal(ByVal t As Range, ByVal r As Range, ByVal c As Range) As Variant
    Dim x As Variant, y As Variant

    x = Application.Match(r.Cells(1, 1).Value, t.Columns(1), 0)
    y = Application.Match(c.Cells(1, 1).Value, t.Rows(1), 0)

    If IsError(x) Or IsError(y) Then
        TabVal = vbNullString
    Else
        TabVal = t.Cells(x, y).Value
    End If
End Function

推荐阅读