programing

VBA Match에서 오류 2042가 표시되는 이유는 무엇입니까?

telecom 2023. 7. 4. 21:40
반응형

VBA Match에서 오류 2042가 표시되는 이유는 무엇입니까?

열 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이라는 값이 실제로 범위 내에 있는지 확인하는 것이었습니다.

다음은 Match 기능에 문자열이 필요해서 시도했습니다.

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

헛되이

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)

이에 대한 부차적인 참고 사항으로, 향후 이 오류가 발생할 경우 오류가 발생할 수 있는 함수와 함께 변형 유형이 매우 잘 작동합니다.

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

객체 브라우저에서 일치 함수를 찾으면 이중으로 반환되므로 변수 CurrentRow를 이중으로 선언하고 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

워크시트가 여러 개 있는 워크북에서 Match 기능을 사용하려고 했을 때 정확히 동일한 오류 메시지가 표시되었습니다.결과를 수신하는 변수에 대해 변수 유형을 사용하면 일치하려는 대상이 없는 경우 실행 오류를 방지할 수 있습니다.하지만 제 실수는 사용된 레인지의 위치에 있었습니다.검색할 범위가 있는 워크시트를 가리켜야 합니다.처음에 워크시트 참조 없이 범위(...)를 사용한 시간은 워크시트를 활성화한 경우에만 기능이 제대로 작동했습니다.

저에게는 타이프 캐스팅 없이도 잘 작동했습니다.둘 다 사용했습니다.

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

그리고.

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

Dimensioned CurrentShipment(정수, 이중, 길이 또는 변형), 모두 정상 작동...

흥미롭게도, 저는 당신의 데이터를 빈 엑셀 시트에 입력하고 당신의 원래 코드 조각을 실행했습니다.CurrentShipment를 String 또는 Long으로 캐스팅하지 않고도 예상대로 3을 반환했습니다.

DIM'ing 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

언급URL : https://stackoverflow.com/questions/15526784/why-am-i-getting-error-2042-in-vba-match

반응형