Home » excel » excel – Find first collection to meet a criteria

excel – Find first collection to meet a criteria

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a collection object with a binary property. It’s a collection of collections in a 2-D format.

Dim colArry(1 to 5, 1 to 3) as New Collection 

The binary property of the collections would look like:

   1    2    3
1  0    0    0
2  0    0    1
3  1    0    0
4  0    0    0
5  0    0    0

The collection property is stored as:

Dim pNumber as Integer    

Public property Get() as Integer
    Number = pNumber
End property
Public property Let Number(value as Integer)
    pNumber = value
End Property 

I want to store the collection reference that has the first row where the property is 1 (across all columns), in new variables.

In the above collections I would want to flag colArray(2,3). If column 3 were all zeros, then I would want to flag colArray(3,1).

I want to flag this by storing the row and column index in two variables:
row = 2
col = 3

The property is read in from an Excel sheet, say starting at cell R1C1 on Sheet1:

for i=1 to 5 
    for j=1 to 3
        colArray(i,j) = ThisWorkbook.Sheets("Sheet1").Cells(i,j)
    Next j
Next i
How to&Answers:

Here is an example:

Option Explicit

Public Sub Example()
    'fill an example array
    Dim ColArray(1 To 5, 1 To 3) As Integer
    ColArray(2, 3) = 1
    ColArray(3, 1) = 1

    'now the ColArray looks like
    '0   0   0
    '0   0   1
    '1   0   0
    '0   0   0
    '0   0   0

    Dim Found As Boolean
    Dim iRow As Long, iCol As Long
    For iRow = LBound(ColArray, 1) To UBound(ColArray, 1) 'loop throug rows
        For iCol = LBound(ColArray, 2) To UBound(ColArray, 2) 'loop throug columns
            If ColArray(iRow, iCol) = 1 Then 'check if value is 1
                Found = True
                Exit For
            End If
        Next iCol
        If Found Then Exit For
    Next iRow

    'found at ColArray(iRow, iCol)
    If Found Then
        Debug.Print "Found at:", iRow, iCol
    Else
        Debug.Print "not 1 found"
    End If
End Sub

Note that you can read a range into an array at once (without looping)

Dim colArray As Variant
colArray = ThisWorkbook.Worksheets("Sheet1").Range("A1:C5").Value