2012-09-10 55 views
3

可能重複:
How do I determine if an array is initialized in VB6?檢查空數組的大小

我聲明一個數組最初作爲空:

Dim ArrayVar() as Variant 


'May add some data, may not 
if something then 
    Redim Preserve ArrayVar(ubound(ArrayVar,1)+1) 
    ArrayVar(ubound(ArrayVar,1)) = "something" 
end if 


'Always check size of array 
if ubound(ArrayVar,1) > x 

問題是有時當我達到檢查大小,沒有添加任何東西 - 數組是空的,我得到一個運行時錯誤。我曾嘗試用Dim ArrayVar(0) as Variant聲明該數組,但是然後redim語句不會編譯。

最好的辦法是做什麼?

+0

這會回答夜q http://stackoverflow.com/questions/206324/how-to-check-for-empty-array-in-vba-macro –

+0

不,說「下標超出範圍」 – mezamorphic

+0

也這將有助於http://stackoverflow.com/questions/10559804/vba-checking-for-empty-array?rq=1 –

回答

2

您可以使用IsEmpty()函數。

請嘗試以下代碼:

Dim ArrayVar() As Variant 

Sub x() 
If IsEmpty(arrvar) Then 
    ReDim ArrayVar(0) 
Else 
    ReDim Preserve ArrayVar(UBound(ArrayVar, 1) + 1) 
    ArrayVar(UBound(ArrayVar, 1)) = "something" 
End If 

MsgBox UBound(ArrayVar, 1) 
End Sub