excel - 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
(标签)?
解决方案
如评论中所述,使用Application.Match
and的方法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
推荐阅读
- node.js - 如何从 MongoDB 获取文档?
- rust - 在选项上调用地图
> 工作方式与在选项上调用它不同 > - html - CSS Height 属性详解
- javascript - 如何从 Javascriopt 中的静态类方法调用非类方法
- azure-devops - 使用 azure devops 部署到离线服务器
- swift - SwiftUI:如何为警报使用 .presentation 修饰符?获得编译器类型检查错误
- php - 有什么方法可以在核心 php 代码中访问 WordPress 数据库
- laravel - 如何在 laravel 中仅订购一次选中复选框产品?
- python - 拥有一个 SQLite 数据库如何只知道表名就遍历所有表项?
- ssl - Kubernetes Ingress SSL 证书问题