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

use*_*261 14 excel vba excel-2007 excel-vba

我有A栏:

+--+--------+
|  |  A     |
+--+--------+
| 1|123456  |
|--+--------+
| 2|Order_No|
|--+--------+
| 3|    7   |
+--+--------+
Run Code Online (Sandbox Code Playgroud)

现在,如果我输入:

=Match(7,A1:A5,0)
Run Code Online (Sandbox Code Playgroud)

进入我得到的纸张上的一个单元格

3
Run Code Online (Sandbox Code Playgroud)

结果是.(这是期望的)

但是当我进入这一行时:

Dim CurrentShipment As Integer
CurrentShipment = 7
CurrentRow = Application.Match(CurrentShipment, Range("A1:A5"), 0)
Run Code Online (Sandbox Code Playgroud)

CurrentRow获取值"Error 2042"

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

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

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

无济于事.

KDT*_*KDT 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
Run Code Online (Sandbox Code Playgroud)


小智 13

请参阅VBA 单元错误值列表:

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!
Run Code Online (Sandbox Code Playgroud)

尝试转换的值CurrentShipmentIntegerLong,而不是到String:

CurrentRow = Application.Match(CLng(CurrentShipment), Range("A1:A5"), 0)
Run Code Online (Sandbox Code Playgroud)

  • 它适用于整数,但不适用于小数而不适用于字符串,所以感觉有点狡猾...... (2认同)