Go to Google Groups Home    microsoft.public.vb.general.discussion
Array Size

Mike D Sutton <mike.sut...@btclick.com>

> The generic formula is

> UBound(MyArray) - LBound(MyArray) + 1

> So, if the array is zero-based then the number of elements becomes

> Ubound(MyArray) + 1

> If the array is 1-based then it is just UBound(MyArray).

This doesn't take into account multi-dimensional or un-initialised arrays
though, for that you'd need something like this:
http://www.mvps.org/vbnet/code/helpers/getarraydims.htm
Here's another solution for you:

'***
Private Type typArrayDim
    adLow As Long
    adHigh As Long
End Type

Private Function ArrSize(ByRef inArr As Variant, _
    ByRef outArr() As typArrayDim) As Long
    Dim TempDim As Long

    Do
        TempDim = -1
        On Error Resume Next
        TempDim = LBound(inArr, ArrSize + 1)
        On Error GoTo 0

        If (TempDim <> -1) Then
            ReDim Preserve outArr(ArrSize) As typArrayDim

            With outArr(ArrSize)
                .adLow = TempDim
                .adHigh = UBound(inArr, ArrSize + 1)
            End With

            ArrSize = ArrSize + 1
        End If
    Loop While (TempDim <> -1)
End Function

Private Sub SayArrayDim(ByRef inArr As Variant)
    Dim ArrDims() As typArrayDim
    Dim NumDims As Long
    Dim LoopDims As Long
    Dim SayDims As String

    NumDims = ArrSize(inArr, ArrDims())
    SayDims = TypeName(inArr)

    If (NumDims) Then
        SayDims = Left$(SayDims, Len(SayDims) - 1)

        For LoopDims = 0 To NumDims - 1
            With ArrDims(LoopDims)
                SayDims = SayDims & .adLow & " To " & .adHigh & _
                    IIf(LoopDims < (NumDims - 1), ", ", "")
            End With
        Next LoopDims

        SayDims = SayDims & ")"
    End If

    MsgBox SayDims
End Sub

Private Sub Form_Load()
    Dim MyArr(1 To 2, 3 To 4, 5 To 6, 7 To 8, 9 To 10) As Long
    Dim EmptyArr() As Long
    Dim MyVar As Long

    Call SayArrayDim(MyArr)
    Call SayArrayDim(EmptyArr)
    Call SayArrayDim(MyVar)
End Sub
'***

Hope this helps,

    Mike

 -- EDais --

 - Microsoft Visual Basic MVP -
WWW: Http://EDais.earlsoft.co.uk/
Work E-Mail: ED...@btclick.com
Other E-Mail: Mike.Sut...@btclick.com