为什么我在VBA比赛中收到错误2042?

时间:2013-03-20 14:45:39

标签: excel excel-vba excel-2007 vba

我有A栏:

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

现在,如果我输入:

=Match(7,A1:A5,0)

进入工作表上的单元格

3

结果。 (这是期望的)

但是当我进入这一行时:

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

CurrentRow获取值“Error 2042”

我的第一直觉是确保值7实际上在范围内,而且确实如此。

我的下一个可能是匹配功能需要一个字符串所以我试过

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

无济于事。

5 个答案:

答案 0 :(得分:15)

作为对此的注意事项以及将来遇到此错误的任何人,如果任何函数返回可能的错误,则变体类型的效果非常好:

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

答案 1 :(得分:10)

请参阅VBA Cell Error Values列表:

Constant    Error number  Cell error value
xlErrDiv0   2007          #DIV/0!
xlErrNA     2042          #N/A
xlErrName   2029          #NAME?
xlErrNull   2000          #NULL!
xlErrNum    2036          #NUM!
xlErrRef    2023          #REF!
xlErrValue  2015          #VALUE!

尝试将CurrentShipment的值从Integer转换为Long而不是转换为String

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

答案 2 :(得分:1)

如果在对象浏览器中查找匹配函数,则返回double,因此我已将变量CurrentRow声明为double,并且它接受3变量参数。如果适用于您,请尝试以下代码。

enter image description here

enter image description here

  Sub sample()

    Dim CurrentShipment As Variant
    CurrentShipment = 7

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

答案 3 :(得分:0)

有趣的是,我将您的数据输入到空白的Excel工作表中,然后运行原始的代码片段。它按预期返回3,而不必将CurrentShipment转换为String或Long。

Not DIM'ing CurrentRow默认情况下使其成为Variant,但即使将它们设置为Integer或CurrentRow也不会产生错误,因此使用Double作为返回类型是多余的。

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

答案 4 :(得分:0)

对我来说,没有任何类型的任何东西,它工作得很好我用过两者:

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

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

Dimensioned CurrentShipment为Integer,Double,Long或Variant,一切正常......