[英]Why am I getting Error 2042 in VBA Match?
我有 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 獲取“錯誤 2042”的值
我的第一直覺是確保值 7 實際上在范圍內,而且確實如此。
我的下一個可能是 Match function 需要一個字符串,所以我嘗試了
Dim CurrentShipment As Integer
CurrentShipment = 7
CurrentRow = Application.Match(Cstr(CurrentShipment), Range("A1:A5"), 0)
無濟於事。
作為補充說明,對於將來遇到此錯誤的任何人,如果任何函數返回可能的錯誤,variant類型都可以很好地工作:
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
請參閱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!
嘗試將CurrentShipment
的值從Integer
轉換為Long
而不是String
:
CurrentRow = Application.Match(CLng(CurrentShipment), Range("A1:A5"), 0)
如果您在對象瀏覽器中尋找匹配函數,它將返回double值,因此我已將CurrentRow變量聲明為double值,同時它接受3個變體參數。 如果適合,請嘗試以下代碼。
Sub sample()
Dim CurrentShipment As Variant
CurrentShipment = 7
Dim CurrentRow As Double
CurrentRow = Application.Match(CurrentShipment, Range("A1:A5"), 0)
End Sub
當我嘗試在包含多個工作表的工作簿中使用 Match function 時,我收到了完全相同的錯誤消息。 如果我們嘗試匹配的主題不存在,則對接收結果的變量使用變體類型可以避免運行錯誤。 但我的錯誤在於所用范圍的位置。 指向具有要搜索范圍的工作表至關重要。 第一次,我在沒有工作表引用的情況下使用 Range(...),function 只有在我激活該工作表時才能正常工作。
有趣的是,我將您的數據輸入到一個空白的Excel工作表中,然后運行您的原始代碼段。 如預期的那樣,它返回3,而不必將CurrentShipment強制轉換為String或Long。
默認情況下,不將DIMinging CurrentRow設為Variant,但即使將它們都設置為Integer或CurrentRow設置為Byte也不拋出錯誤,因此使用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
對我來說,它可以正常工作,而無需進行任何類型的轉換。 我都用:
Application.WorksheetFunction.Match(CurrentShipment, Range("A1:A5"), 0)
和
Application.Match(CurrentShipment, Range("A1:A5"), 0)
尺寸為CurrentShipment的整數,雙精度,長整型或可變型,都可以正常工作...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.