Friday, February 12, 2016

Excel VBA- Array Concept

By Ajeet Kumar

The following examples can be used to conceptualize the dimensions and size of an array. Simply run the following codes in the code window and the results are quite informative and self-explanatory.

Option Explicit


Sub ArrStatic()

    Dim Arr1(1)
    Dim Arr2(3 To 50)
    Dim Arr3(-11 To 99)

    Arr1(0) = 1

    Arr1(1) = 3
    
    Debug.Print "Arr1 has Lower Bound " & LBound(Arr1) & " and Upper Bound " & UBound(Arr1) & "."
    Debug.Print "Arr2 has Lower Bound " & LBound(Arr2) & " and Upper Bound " & UBound(Arr2) & "."
    Debug.Print "Arr3 has Lower Bound " & LBound(Arr3) & " and Upper Bound " & UBound(Arr3) & "."
    
    Debug.Print "Arr1 can contain " & UBound(Arr1) - LBound(Arr1) + 1 & " elements."
    Debug.Print "Arr2 can contain " & UBound(Arr2) - LBound(Arr2) + 1 & " elements."
    Debug.Print "Arr3 can contain " & UBound(Arr3) - LBound(Arr3) + 1 & " elements."
    
    Debug.Print Arr1(0)
    Debug.Print Arr1(1)

End Sub


Sub ArrStaticMultiDim()

    Dim Arr2DX(1 To 4, 1 To 6)
    Dim Arr2DY(3, 5)
    
    Debug.Print LBound(Arr2DX) '' of ROW
    Debug.Print UBound(Arr2DX) '' of ROW
    Debug.Print LBound(Arr2DY) '' of ROW
    Debug.Print UBound(Arr2DY) '' of ROW
    
    Debug.Print LBound(Arr2DX, 1) ''OF 1ST DIM
    Debug.Print UBound(Arr2DX, 1) ''OF 1ST DIM
    Debug.Print LBound(Arr2DY, 1) ''OF 1ST DIM
    Debug.Print UBound(Arr2DY, 1) ''OF 1ST DIM

    Debug.Print LBound(Arr2DX, 2) ''OF 2ND DIM

    Debug.Print UBound(Arr2DX, 2) ''OF 2ND DIM
    Debug.Print LBound(Arr2DY, 2) ''OF 2ND DIM
    Debug.Print UBound(Arr2DY, 2) ''OF 2ND DIM
    
End Sub

Sub Fill1DArr()


    Dim Arr(5)

    Dim ArrT(1 To 5)
    Dim intX As Integer
    
    For intX = LBound(Arr) To UBound(Arr)
        Arr(intX) = intX
        Debug.Print Arr(intX)
    Next
    Debug.Print "Arr can hold " & UBound(Arr) - LBound(Arr) + 1 & " elements."
        
    For intX = LBound(ArrT) To UBound(ArrT)
        ArrT(intX) = intX
        Debug.Print ArrT(intX)
    Next
    
    Debug.Print "ArrT can hold " & UBound(ArrT) - LBound(ArrT) + 1 & " elements."
    
End Sub

Sub Fill2DArr()


    Dim Arry(1 To 5, 2 To 7)

    Dim lngR As Long
    Dim lngC As Long
    
    For lngR = LBound(Arry, 1) To UBound(Arry, 1)
        For lngC = LBound(Arry, 2) To UBound(Arry, 2)
            Arry(lngR, lngC) = lngR & ", " & lngC
            Debug.Print Arry(lngR, lngC)
        Next
    Next
    Range("A1").CurrentRegion.Clear
    Range("A1").Resize(5 - 1 + 1, 7 - 2 + 1) = Arry

End Sub





Hot Topics