例如,当我在TextBox1 = Sara中编写内容时,我需要知道某个名称的索引号,然后单击按钮, 然后,TextBox2应该在表(Table1)中返回与该名称相反的索引值
我在单元格工作表上尝试了INDEX / Match方法,并且它起作用了,但是我尝试将其转换为vba代码,但是我收到了msgbox的提示
运行时1004无法获取worksheetFunction类的match属性。
我的代码是
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。
答案 0 :(得分:2)
如果您使用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测试该错误值。