2013-05-08 57 views
6

不好意思問這樣一個基本的問題,但是這是推動我瘋了VBA數組的長度......(不UBOUND或ONERROR!)

在VBA什麼函數返回一個數組中......即當元素的個數數組是空的,它會返回0?

我不能這樣做與UBound,因爲它在一個空數組上調用時會拋出一個錯誤,我不能相信通過使用OnError來首先確定它是否爲空或者不這樣做的方式...正如論壇上的建議! array.Length抱怨一個錯誤的限定符或什麼的。

我真的需要這樣做:

dim termAry() as String 
populate termAry 
... 

private sub populate(terms() as String) 
    redim preserve terms(terms.Length) ' Redim takes ubound for array size 
    terms(ubound(terms)) = "something really annoying" 
end sub 

P.S任何好的鏈接了一組簡明的VBA語言和函數的引用將是非常有用...... MSDN似乎真的晦澀!

+0

你想要做什麼?你需要一個數組來源 - 它來自哪裏 – 2013-05-08 11:28:57

+1

請參閱http://stackoverflow.com/questions/4097021/vba-handle-empty-array-error或http://stackoverflow.com/questions/206324/how -to-check-for-empty-array-in-vba-macro – 2013-05-08 11:29:04

+0

所有你需要處理的事情就是說如果ubound(arr)> 1那麼...',初始化時使用'redim arr(MAX) – 2013-05-08 11:35:19

回答

10

我相信唯一的方法是使用On Error並處理Subscript Out of Range錯誤,如果數組(或您感興趣的數組維度)未初始化,將會引發該錯誤。

E.g.

Public Function IsInitialized(arr() As String) As Boolean 
    On Error GoTo ErrHandler 
    Dim nUbound As Long 
    nUbound = UBound(arr) 
    IsInitialized = True 
    Exit Function 
ErrHandler: 
    Exit Function 
End Function 

Dim a() As String 
Dim b(0 To 10) As String 

IsInitialized(a) ' returns False 
IsInitialized(b) ' returns True 

您可以將其推廣到測試數組中有多少維,例如,

Public Function HasAtLeastNDimensions(arr() As String, NoDimensions As Long) As Boolean 
    On Error GoTo ErrHandler 
    Dim nUbound As Long 
    nUbound = UBound(arr, NoDimensions) 
    HasAtLeastNDimensions = True 
    Exit Function 
ErrHandler: 
    Exit Function 
End Function 

Dim a() As String 
Dim b(0 To 10) As String 
Dim c(0 To 10, 0 To 5) As String 

HasAtLeastNDimensions(a, 1) ' False: a is not initialized 
HasAtLeastNDimensions(b, 1) ' True: b has 1 dimension 
HasAtLeastNDimensions(b, 2) ' False: b has only 1 dimension 
HasAtLeastNDimensions(c, 2) ' True: c has 2 dimensions 

UPDATE

在迴應評論:

我是正確的思維,該功能不能很容易地推廣到任何數組類型操作

它可以很容易地通過將參數設置爲Variant來泛化,並檢查它是f體內的數組使用IsArray功能:

Public Function HasAtLeastNDimensions(arr As Variant, NoDimensions As Long) As Boolean 
    On Error GoTo ErrHandler 
    Dim nUbound As Long 
    If Not IsArray(arr) Then Exit Function 
    nUbound = UBound(arr, NoDimensions) 
    HasAtLeastNDimensions = True 
    Exit Function 
ErrHandler: 
    Exit Function 
End Function 
+0

謝謝喬......這是邪惡的,但無論如何,謝謝! – user2361340 2013-05-08 12:12:46

+0

這對字符串數組工作正常,我是正確的認爲該函數不能簡單地推廣到操作任何數組類型......它似乎需要與元素明智類型鑄造深層複製? – user2361340 2013-05-08 12:35:53

+0

@ user2361340 - 請參閱更新 – Joe 2013-05-08 13:17:58