VBA匹配函数“方法'匹配'对象'WorksheetFunction'失败”

时间:2015-06-10 14:32:57

标签: excel vba excel-vba

我正在尝试在Excel中的编程项目中使用Match VBA函数来获取第一个行号,其中包含“1”。我正在使用的代码是:

Dim BorradorVar As Integer
BorradorVar = WorksheetFunction.Match(1, Sheets("Usuarios").Range("A1,A100"), 0)

有人可以解释我做错了什么吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您应该将Range称为

Range("A1:A100")

而不是

Range("A1,A100")

使用逗号,您只能引用A1A100

另外,如果您不确定是否匹配,可以使用Application.Match并将结果存储在Variant变量中。区别在于Application.Match失败时会返回错误,然后您可以检查它是否失败。

示例(检查MSDN是否有完整代码):

Dim var As Variant

var = Application.Match(Cells(iRow, 1).Value, Worksheets(iSheet).Columns(1), 0)

If Not IsError(var) Then
    Debug.Print "There is actually a match"
Else
    Debug.Print "No match found"
End IF

警告:如果您在行32,767 your code will not run之后匹配,则因为它超出了Integer的范围。我建议使用Long代替IntegerUsing Long is better practice in VBA无论如何。

最后请注意,如果有人更改了工作表的名称,则此代码将无法运行。 It is safer to refer to the worksheet by using its sheet ID instead of its name(免责声明:我已经写了对该问题的公认答复)。