为什么我在VBA匹配中遇到错误2042?

我有专栏A:

+--+--------+ | | A | +--+--------+ | 1|123456 | |--+--------+ | 2|Order_No| |--+--------+ | 3| 7 | +--+--------+ 

现在,如果我input:

 =Match(7,A1:A5,0) 

到我得到的表单元格中

 3 

结果是。 (这是需要的)

但是当我input这行时:

 Dim CurrentShipment As Integer CurrentShipment = 7 CurrentRow = Application.Match(CurrentShipment, Range("A1:A5"), 0) 

CurrentRow得到一个值“Error 2042”

我的第一本能是确保价值7实际上在这个范围内,而且是这样的。

我的下一个可能是匹配function需要一个string,所以我试过了

 Dim CurrentShipment As Integer CurrentShipment = 7 CurrentRow = Application.Match(Cstr(CurrentShipment), Range("A1:A5"), 0) 

无济于事。

尝试这个 :

 CurrentRow = Application.Match(CLng(CurrentShipment), Range("A1:A5"), 0) 

作为对此的一个注意事项,并且对于任何将来出现这个错误的人,任何函数都会返回一个可能的错误,这个变体的types工作得很好:

 Dim vreturn as variant vreturn = Application.Match(CurrentShipment, Range("A1:A5"), 0) ' this could be any function like a vlookup for example as well If IsError(vreturn) Then ' handle error Else CurrentRow = cint(vreturn) End If 

如果在对象浏览器中查找匹配函数,则返回double,所以我声明variablesCurrentRow为double,而它接受3variables参数。 尝试下面的代码,如果它适合你。

在这里输入图像说明

在这里输入图像说明

  Sub sample() Dim CurrentShipment As Variant CurrentShipment = 7 Dim CurrentRow As Double CurrentRow = Application.Match(CurrentShipment, Range("A1:A5"), 0) End Sub 

对我来说,没有types铸造任何东西,它工作正常 我用了两个:

Application.WorksheetFunction.Match(CurrentShipment, Range("A1:A5"), 0)

Application.Match(CurrentShipment, Range("A1:A5"), 0)

尺寸的CurrentShipment整数,双,长或变种,都工作正常…

有趣的是,我把你的数据input到一张空白的Excel表格中,然后运行你原来的代码片段。 如预期的那样,它返回了3,而不必将string或Long作为CurrentShipment。

不DIM'ing CurrentRow使默认情况下它是一个Variant,但即使将它们都设置为Integer或CurrentRow作为字节不会引发错误,所以使用Double作为返回types是多余的。

 Sub Match() Dim CurrentShipment As Integer Dim CurrentRow As Byte '<--- NOTE CurrentShipment = 7 CurrentRow = Application.Match(CurrentShipment, Range("A1:A5"), 0) MsgBox CurrentRow End Sub