将特定行添加到另一个数组

时间:2018-02-09 10:22:57

标签: arrays excel vba excel-vba sorting

我有一个代码,它遍历所有行并查看第I列是否包含单词' MISS'并将其添加到数组中。我现在想要知道那些行存储在其中,而是将已经不在数组中的行存储到不同的数组中。我目前的代码是:

Sub tester()

max_targets = 6
Dim RowsToMiss(1 To 6)

lRow = 2
Do Until Sheets("Result").Cells(lRow, 1) = ""
    If Sheets("Result").Cells(lRow, 9) = "MISS" Then
        RowsToMiss(Sheets("Result").Cells(lRow, 4)) = lRow
    End If
    lRow = lRow + 1
Loop

lRow = 2
Do Until Sheets("Result").Cells(lRow, 1) = ""
    If RowsToMiss(Sheets("Result").Cells(lRow, 4)) <> lRow Then
        'read the row in!
        Else
    End If
    lRow = lRow + 1
Loop
End Sub

2 个答案:

答案 0 :(得分:2)

如果需要动态地向集合添加值,VBA会提供类型Collection,这比Array更好,因为它的大小可以动态增加。因此,在您的情况下,您需要遍历第二列,检查单元格中的值并将它们添加到两个可用集合之一:

Option Explicit

Sub TestMe()

    Dim withMiss        As New Collection
    Dim withoutMiss     As New Collection
    Dim currentRow      As Long

    currentRow = 2
    With Worksheets(1)
        Do Until .Cells(currentRow, 1) = vbNullString
            If UCase(.Cells(currentRow, 1)) = "MISS" Then
                withMiss.Add currentRow
            Else
                withoutMiss.Add currentRow
            End If
        currentRow = currentRow + 1
        Loop
    End With

    Dim cnt As Long

    Debug.Print "Rows with MISS"
    For cnt = 1 To withMiss.Count
        Debug.Print withMiss.item(cnt)
    Next cnt

    Debug.Print "Rows without MISS"
    For cnt = 1 To withoutMiss.Count
        Debug.Print withoutMiss.item(cnt)
    Next cnt

End Sub
如果2,3,4&amp; 1.列的8个单元格带有&#34; MISS&#34;:

Rows with MISS
 2 
 3 
 4 
 8 
Rows without MISS
 5 
 6 
 7 

答案 1 :(得分:1)

就像@brainac一样,我不确定你在问什么,但却采取了行动。这将创建另一个数组,用于存储不包含MISS的行号。

Sub tester()

Dim max_targets As Long, lRow As Long, i As Long

max_targets = 6
Dim RowsToMiss(1 To 6)
Dim RowsToHit()

For lRow = 2 To Sheets("Result").Cells(Rows.Count, 1).End(xlUp).Row
    If Sheets("Result").Cells(lRow, 9) = "MISS" Then
        RowsToMiss(Sheets("Result").Cells(lRow, 4)) = lRow
    Else
        i = i + 1
        ReDim Preserve RowsToHit(1 To i)
        RowsToHit(i) = lRow
    End If
Next lRow

End Sub