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

1
  • 3
    One of those rare submissions where the answer is within the question. :) Commented Aug 2, 2014 at 16:20

3 Answers 3

12

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.

3
  • Oh what a fool I've been ... Thanks Ѿ Commented Aug 2, 2014 at 15:04
  • 3
    If I answered your question, please mark it as the solution! Thanks Commented Aug 2, 2014 at 16:06
  • This solution is wrong, on an empty array you will get every time a size of 1,which is not what you want! Commented Aug 8, 2022 at 12:20
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.

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.