VBA 错误处理(INDEX/MATCH in Excel)
VBA error handling (INDEX/MATCH in Excel)
在 Excel 中,可以使用 INDEX 和 MATCH 函数从一个范围中查找值;
通常使用以下表达式:
=INDEX(tablerange,MATCH(rowval,col1range,0),MATCH(colval,row1range,0))
但是,由于我经常需要此功能,因此我创建了自己的简单自定义 VBA 函数 TabVal()
,其中 returns 根据标题 [=] 中的给定值从给定范围内取值28=]:
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
的方法:
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
尝试,
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
在 Excel 中,可以使用 INDEX 和 MATCH 函数从一个范围中查找值;
通常使用以下表达式:
=INDEX(tablerange,MATCH(rowval,col1range,0),MATCH(colval,row1range,0))
但是,由于我经常需要此功能,因此我创建了自己的简单自定义 VBA 函数 TabVal()
,其中 returns 根据标题 [=] 中的给定值从给定范围内取值28=]:
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
的方法:
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
尝试,
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