查找符合条件的第一个集合

时间:2019-07-15 09:42:01

标签: excel vba

我有一个带有二进制属性的收集对象。它是二维格式的集合的集合。

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

集合的二进制属性如下:

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

集合属性存储为:

Dim pNumber as Integer    

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

我要在新变量中存储属性为1(在所有列中)的第一行的集合引用。

在以上集合中,我想标记colArray(2,3)。如果第3列全为零,那么我想标记colArray(3,1)

我想通过将行索引和列索引存储在两个变量中来对此进行标记: row = 2 col = 3

从Excel工作表中读取该属性,例如从Sheet1的单元格R1C1开始:

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

1 个答案:

答案 0 :(得分:2)

这里是一个例子:

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

请注意,您可以一次将一个范围读入数组(不循环)

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