Gurkenhobel
Gurkenhobel

Reputation: 59

VBS: Counting number of items in an Array

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

Upvotes: 5

Views: 32345

Answers (3)

Thomas
Thomas

Reputation: 1195

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

Upvotes: 1

JaGoTu
JaGoTu

Reputation: 176

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.

Upvotes: 11

shahkalpesh
shahkalpesh

Reputation: 33476

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.

Upvotes: 1

Related Questions