【问题标题】:VBA error handling (INDEX/MATCH in Excel)VBA 错误处理(Excel 中的索引/匹配)
【发布时间】:2021-01-28 03:18:23
【问题描述】:

在 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(标签)更好的错误处理方法?

【问题讨论】:

  • 使用Application.Match 并使用IsError 测试结果是否错误。
  • 请注意,这里根本不需要使用IndexTabVal = t.Cells(x, y).Value
  • Dim x As Variant, y As Variant 如果你使用Application.Match
  • 感谢@BigBen,只是认为甚至不需要 Index()。但是我想要像 If( ! TabVal = t.Cells(x,y).Value ) Then TabVal="" 这样的语法
  • 这个语法到底是什么意思?

标签: excel vba exception excel-formula office365


【解决方案1】:

如 cmets 中所述,一种使用 Application.MatchIsError 的方法:

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

【讨论】:

  • 就是这样,我只是不喜欢带有 GoTo errorhandler 标签的中断编程。我更喜欢 IF 结构。
【解决方案2】:

试试,

Public Function TabVal(ByVal t As Range, ByVal r As Range, ByVal c As Range)
    Dim x As Variant, y As Variant
    Dim rng As Range
    
    For Each rng In t.Columns(1).Cells
        If rng = r Then
            x = rng.Row
            Exit For
        End If
        
    Next rng
    For Each rng In t.Rows(1).Cells
        If rng = c Then
            y = rng.Column
            Exit For
        End If
    Next rng
    
    If IsEmpty(x) Or IsEmpty(y) Then
    Else
        TabVal = Cells(x, y).Value
    End If
End Function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 2014-03-28
    • 1970-01-01
    • 2011-11-26
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多