PDA

View Full Version : Array Help



bjoshi
12-29-2011, 11:44 PM
Hi,

I'm trying to work with arrays for the first time. Here is the kind of code that I wish to do,

1. I need to check whther a value is present in an Array, if not, then add the value to the array, check the next value, if not present in the array, then add the value to the array....so on...

2. After every addition of an element to the array, i want a msgbox stating that "the last value of the array is now...."

3. Also, I want the array to contain only say 10 elements, so if the value is not present in the array and the number of elements in the array is 10 then the value being tested should be added to a new array. so if there are 21 values i am checking then 3 arrays would be created, 10+10+1=21.

Hopefully I've been clear in my explanation. Any help is appreciated.

Thanks and have a good day ahead.
bjoshi

Kenneth Hobs
12-30-2011, 07:58 AM
Sounds like a homework problem.

Arrays can not be created dynamically. If you have a set number then you can create them as needed. You will need to use Redim.

A dictionary object works well as it has an Exists property.

If not a homework problem, this will get you started.
Sub Test_PosInArray()
Dim a() As Variant
a() = Array("Hello World!", "Hi!", "Greetings!")
MsgBox PosInArray("test", a()), vbInformation, "test: in a()"
MsgBox PosInArray("world", a()), vbInformation, "world: in a()"
MsgBox PosInArray("hello world!", a()), vbInformation, "hello world!: in a()" 'Note: Not case sensitive.
End Sub

'If array is 0 based, 1 is returned if aValue matches anArray(0).
Function PosInArray(aValue, anArray)
Dim pos As Long
On Error Resume Next
pos = -1
pos = WorksheetFunction.Match(CStr(aValue), anArray, 0)
PosInArray = pos
End Function

bjoshi
12-30-2011, 11:47 PM
Hi Kenneth,

Not quite the way i imagined, but i'll try to make this work anyways. Thanks for helping :)

Regards,
bjoshi