5

How could I investigate simply the number of items in a given array. I used this code, but it's a bit laborious

myArr=Array("frog", "cat", "bat", "rat", "horse")
 for i=0 to UBound(myArr)
 ' Msgbox i +1 & ".item: " & myArr(i) 
 next
Msgbox i & " items in this array:" & vbcrlf & Join(myArr)

Thanks

Gurkenhobel
  • 63
  • 1
  • 1
  • 6

3 Answers3

11

Umm... you have it in your code. UBound(Array) returns the upper bound, which is the highest existing item. UBound(myArr) + 1 is its length, because the index is zero based.

JaGoTu
  • 176
  • 4
1

Msgbox (ubound(myArr) + 1) & " items in this array:" & vbcrlf & Join(myArr)

EDIT: While you are using ubound already, why do you need a loop & a variable i to count.

shahkalpesh
  • 33,172
  • 3
  • 63
  • 88
0

The right answer is

Msgbox (UBound(myArr)-LBound(myArr)+1) & " items in this array:" & vbcrlf & Join(myArr)

This gives you the right item count also when your array is empty.

Check also https://stackoverflow.com/a/30574874/1426827

Thomas
  • 1,193
  • 1
  • 7
  • 16