How to lookup a literal number in a .net ArrayList from VBA?

Viewed 128

The .net runtime is exposed to VBA (and other COM clients) via mscorlib.dll. In theory this means a VBA programmer can use .net classes.

I have used an ArrayList for sorting, and was trying to call other methods but for the IndexOf I have hit a problem. It won't take a literal for the paramter, it is expecting an Object. I thought maybe a boxed integer might work but that failed as well.

So how to lookup a literal number in an ArrayList from VBA?

Sub Test()
    Dim obj As Object
    Set obj = CreateObject("System.Collections.ArrayList")
    obj.Add 4
    obj.Add 8
    obj.Add 12
    obj.Add 16
    obj.Add 20
    Debug.Assert obj.Count() = 5
    Debug.Assert obj.Item(2) = 12

    '* try a literal
    Debug.Print obj.IndexOf(12) 'ERRORS err.Description=Invalid procedure call or argument

    '* try a boxed integer
    Dim boxedInteger As mscorlib.Int32
    boxedInteger.m_value = 12

    Debug.Print obj.IndexOf(boxedInteger) 'ERRORS err.Description=Invalid procedure call or argument

End Sub
1 Answers

Add argument 0

Debug.Print obj.IndexOf(12, 0)

IndexOf

The property .IndexOf indicates the position (=index number) of an item in an ArrayList.

The first argument is the value you are looking for, the second one the position after from which you want to check the existence of the value


The above link definition is that the second argument behaviour is after, whereas it is in fact starting from. The website author is updating to reflect this. That is in line with the overload method IndexOf(Object, Int32), in terms of the second argument:

returns the zero-based index of the first occurrence within the range of elements in the ArrayList that extends from the specified index to the last element.

For example, Debug.Print obj.IndexOf(4, 0) , will correctly return 0. I would be interested in some documentation that covers this behaviour, where clearly an object is not passed as first agument. I haven't yet found any.

Related