-1
Sub Test4()

Public Function GetLength(a As Variant) As Integer
   If IsEmpty(a) Then
      GetLength = 0
   Else
      GetLength = UBound(a) - LBound(a) + 1
   End If




End Function

Essentially trying to find the length of two arrays, and am a little confused on how to use this code to do so. Unsure of what to place where and how to make it work without errors. Any help would be appreciated!

Lex
  • 1
  • 1
  • 2
  • 1
    If you are going to have check `IsEmpty` for `a`, you may also want to check whether `Not IsArray` for it too. – Chronocidal Apr 14 '20 at 10:14
  • Thank you for the help, will get back if I come across any difficulties – Lex Apr 15 '20 at 09:23
  • @Lex, if it has solved your issues, you should return the favor and accept an answer. And upvote those that helped once you able to do so. It's simply how the website works =) – JvdV Apr 15 '20 at 10:21
  • Does this answer your question? [Get length of array?](https://stackoverflow.com/questions/30574814/get-length-of-array) – chaotic3quilibrium Aug 02 '21 at 14:16

2 Answers2

2

Are you confused because you need to seperate the function from your sub? You should call that function something like:

Sub Test4()
    Dim arr As Variant
    arr = Array(1, 2, 3)
    If IsArray(arr) Then Debug.Print GetLength(arr)
End Sub

Public Function GetLength(a As Variant) As Long
    GetLength = UBound(a) - LBound(a) + 1    
End Function

I left out IsEmpty if you are to always initialize arr, but put it back if you want to. Just in general, if you are confused on how to call functions and return their values. Have a look at the MS Docs.

JvdV
  • 70,606
  • 8
  • 39
  • 70
  • 1
    @Chronocidal, the idea of `Not IsArray` is a good one. Implemented if you don't mind. Though, I'd personally check it before returning any value since OP wants to check arrays and arrays alone. – JvdV Apr 14 '20 at 10:20
0

The Parameter a represents your Array. The function will return the length of the first dimension of the array it receives as an Argument:

Sub TestIt()
    Dim MyArray As Variant
    MyArray = Split("A,B,C,D,E,F", ",") 'create an Array of Length 6
    MsgBox GetLength(MyArray) 'Output the length of the array, "6"
End Sub

As noted, this may give unexpected results for a 2D array:

[[A][B][C]
 [D][E][F]]

This is a 2-by-3 array, so GetLength will tell you that the length is 2. However, the number of elements in the array is 6

(Note - if this is being used in VBA, then there is no advantage to using Integer instead of Long, and I would recommend you change that line - especially since UBound and LBound both return Longs. With too large an array, you could get an Overflow error!)

Chronocidal
  • 6,827
  • 1
  • 12
  • 26