Excel VBA:无法获得匹配,错误“无法获取WorksheetFunction类的匹配属性”
对于一切美好的爱情,我似乎无法得到这个工作。 我不断收到上面提到的错误。
我有这个表,我试图找出代码是否匹配它自己的子代码在另一列内的其他地方,但它是错误的。 非常感谢您的帮助。
Sub testing() Dim m1 As long Dim myrange As Range Set myrange = Worksheets("Sheet1").Range("B2:B23") For e = 2 To 23 m1= Application.WorksheetFunction.Match(Cells(e, 1).Value, myrange, 0) If m1 > 0 Then Cells(e, 3).Value = "Yes" Else Cells(e, 3).Value = "No" End If Next e MsgBox "Complete!" End Sub
使用Application.Match
函数可以更好地捕捉错误。 当使用WorksheetFunction.Match
,当找不到匹配项时,它会返回一个错误,这就是你正在经历的。
If Not IsError(Application.Match(Cells(e, 1).Value, myrange, 0)) Then 'Do stuff when the match is found Cells(e, 3).Value = "Yes" Else: Cells(e, 3).Value = "No" End If
你也可以使用CountIf
函数:
If Application.WorksheetFunction.CountIf(myRange, Cells(e,1).Value) > 0 Then Cells(e,3).Value = "Yes" Else: Cells(e,3).Value = "No" End If
这两种方法都不需要使用m1
variables,如果需要确定匹配的位置 ,则可以在If/Then
语句的True
部分中分配此variables。
就像另一个选项一样,这也可以通过将下面的公式放在C2单元格中,并将其拖动到C23来完成。
=IF(COUNTIF($A$2:$A$23,B2)>=1,"YES","NO")