count array element in word vba

S

scott

hi

I have a snippet of code that take a given string and uses 'split' to pop it
into an array for me

the string is being split with the space char as the seperator

the problem is that sometimes the string will contain x2 words, other times
x3 or x4

is there a way to count or return the number of array elements being created
from the split ?

code below

<snip>
'need to split aircraft names up for displayy purposes
strAircraft = Trim(AirCraftBox.Value)
arrAircraft = Split(strAircraft)

'most planes have 3 part names
If Count.arrAircraft() > 2 Then
strAircraft_Make = arrAircraft(0)
strAircraft_Model = arrAircraft(1) & " " &
arrAircraft(2)
'gulfs have 2 part names only
Else
strAircraft_Make = arrAircraft(0) & " " &
arrAircraft(1)
End If
</snip>

obviously this is not working, is there a method for dealing with this ? or
will I have to loop through all elements to determin how many there are
(seems a little inefficient that way round !)

thanks

_scott
 
P

Peter Hewett

Hi Scott

Use the UBound function, something like:

UBound(Split("Hello world it's a lovely day", " "))
this would return "5". Note the lower boundary is 0, for a total of 6
elements.

So you can use:
UBound(arrAircraft)

HTH + Cheers - Peter
 
J

Jezebel

As the others have mentioned, Ubound() tells you. For rock-solid code, you
should also use LBound() -- then you are making no assumptions at all about
the array indices.

Dim pIndex as long

'Get the Make
pIndex = LBound(arrAircraft)
strAircraft_Make = arrAircraft(pIndex)

'Get the first word of the Model
pIndex = pIndex + 1
strAircraft_Model = arrAircraft(pIndex)

'Get any additional Model words, however many there are
Do while pIndex < Ubound(arrAircraft)
pIndex = pIndex + 1
strAircraft_Model = strAircraft_Model & " " & arrAircraft(pIndex)
Loop


But if the first word is always the Make and the remainder the Modal,
instr() to find the first space is easier.

pIndex = instr(strAircraft, " ")
strAircraft_Make = left(strAircraft, pIndex - 1)
strAircraft_Model = mid(strAircraft, pIndex + 1)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top