2014-10-10 10 views
-2

이러한 if ... then statements가 제 의견으로 잘못된 결과를 얻고 있습니다. 첫 번째는 '참'이어야 할 때 '거짓'값을 반환합니다. 네 번째 값은 올바른 값을 반환합니다. 두 번째와 세 번째는 오류를 반환합니다.배열이 비어 있는지 확인하십시오 (vba excel)

Sub empty_array() 
    Dim arr1() As Variant 

    If IsEmpty(arr1) Then 
    MsgBox "hey" 
    End If 

    If IsError(UBound(arr1)) Then 
    MsgBox "hey" 
    End If 

    If IsError(Application.match("*", (arr1), 0)) Then 
    MsgBox "hey" 
    End If 

    ReDim arr1(1) 
    arr1(1) = "hey" 

    If IsEmpty(arr1) Then 
    MsgBox "hey" 
    End If 
End Sub 

답변

8

는 Arr1은 코드의 첫 번째 문으로 '변형'의 배열이된다 : 빈 상자가 현실 세계에 존재하는 등의 사이즈는 제로

Dim arr1() As Variant 

배열이 비어 있지 않습니다.

'Variant'변수를 정의하면 변수가 생성 될 때 비어있게됩니다.

다음 코드는 "비어 있음"을 표시합니다.

Dim a as Variant 

If IsEmpty(a) then 
    MsgBox("Empty") 
Else 
    MsgBox("Not Empty") 
End If 
0

추가 내용 : 배열이 정의 된 것과 관계가 있습니다. 고려 :

dim a() as integer 
dim b() as string 
dim c() as variant 

'these doesn't work 
if isempty(a) then msgbox "integer arrays can be empty" 
if isempty(b) then msgbox "string arrays can be empty" 

'this is because isempty can only be tested on classes which have an .empty property 

'this do work 
if isempty(c) then msgbox "variants can be empty" 

그래서 우리는 무엇을 할 수 있습니까? 우리가 오류를 트리거 어떻게 든 처리를, 예를

dim a() as integer 
dim bEmpty as boolean 

bempty=false 

on error resume next 
bempty=not isnumeric(ubound(a)) 
on error goto 0 

을위한 그러나이 정말 서투른 수있는 경우 VBA에서, 우리가 볼 수 ... 더 좋은 솔루션은 부울 변수를 선언하는 것입니다 (공용 또는 모듈 수준이다 베스트). 배열이 처음 초기화 될 때이 변수를 설정하십시오. 변수가 동시에 선언 되었기 때문에 값이 손실되면 배열을 다시 초기화해야한다는 것을 알게됩니다. 그러나 초기화 된 경우 낮은 비용으로 부울 값을 확인하는 것이 전부입니다. 저비용 여부와 자주 점검 할 필요가 있는지 여부에 달려 있습니다.

option explicit 

'declared at module level 
dim a() as integer 
dim aInitialised as boolean 

sub DoSomethingWithA() 
if not aInitialised then InitialiseA 
'you can now proceed confident that a() is intialised 
end sub 

sub InitialiseA() 
'insert code to do whatever is required to initialise A 
'e.g. 
redim a(10) 
a(1)=123 
'... 
aInitialised=true 
end sub 

마지막으로 할 일은 함수를 만드는 것입니다. 이 경우에는 오류 발생시에 서투른 방법에 의존해야합니다.

function isInitialised(byref a() as variant) as boolean 
isInitialised=false 
on error resume next 
isinitialised=isnumeric(ubound(a)) 
end function 
관련 문제