0

I would like to know if there is a way of knowing if parameter can be iterated over using For Each loop before using it.

Method AddRange

This method can accept various data types. Ideally, user would pass an container which contains 0 or more items.

' Class name - Employees
Private pItems As New Collection
Public Sub AddRange(ByVal Items As Variant)

    ' Here should be logic of detecting if Items can be iterated over.
    ' If Items is not a container, throw an error.
    ' Otherwise, proceed with adding items.

    Dim Item As Variant
    For Each Item In Items
        pItems.Add Item
    Next Item

End Sub

Client code

Public Sub Start()

    Dim Emps As New Employees
    Dim Department As New Collection 'of Employees
    Emps.AddRange Department

    Dim AnotherDepartment(0) As Variant 'of Employees
    Emps.AddRange AnotherDepartment

    Dim NewJoiners As New Employees
    Emps.AddRange NewJoiners

    ' This should not work.
    Dim EmployeeName As String
    Emps.AddRange EmployeeName

End Sub
FlameHorizon
  • 199
  • 10
  • `For Each` looks for a special property [`_NewEnum`](https://stackoverflow.com/q/20194919/11683). If there is one, then the object can be iterated over. Arrays don't have it, they can be iterated because `IsArray()` is `True` for them - but then you need to know in advance that it's a 1D array. – GSerg Jan 09 '20 at 14:10
  • @GSerg Could you post that as an Answer with an example of how to use it? I can see it as a "Hidden Member" - and it's a method, not a property - but can't see how to return anything from it. All I can get is an error if something is *not* enumerable and no error if it is. – Cindy Meister Jan 09 '20 at 14:23
  • 1
    Why would I need to know that _but then you need to know in advance that it's a 1D array_ ? I think you can use `For each` with multi dimensional array as well. Or am I getting you wrong? – Storax Jan 09 '20 at 14:25
  • Disadvantage of `for each` for arrays is though that it is read only! – Storax Jan 09 '20 at 14:34
  • @Storax Yep, I confused it with something else. You can `for each` a multidimension array. – GSerg Jan 09 '20 at 16:02
  • @FlameHorizon There's not enough to make it an answer in my opinion, I just pointed you in the right direction. If you want an example of how to use it, see e.g. https://stackoverflow.com/q/26721017/11683. If you want to implement it from scratch, then I haven't done it and can't help you there. – GSerg Jan 09 '20 at 16:06
  • @GSerg Thanks for your input. – FlameHorizon Jan 09 '20 at 16:32

0 Answers0