使用 「For Each...Excel 中的 Next“ 迴圈

摘要

Microsoft Excel 2002 和更新版本的 Excel 會刪除「For Each...Next“ 迴圈的方式與 Microsoft Excel 97 和舊版 Excel 不同。

本文說明差異,並提供Visual Basic for Applications 宏範例,說明如何刪除迴圈中的單元格。

其他相關資訊

Microsoft 提供的程式設計範例僅供說明之用,並不具任何明示或暗示的責任擔保。 這包括 (但不限於) 任何目的之適售性及適用性的暗示責任擔保。 本文假設您熟悉示範的程式設計語言,也熟悉用以建立和偵錯程序的工具。 Microsoft 支援工程師可協助說明特定程序的功能。 不過,他們不會修改這些範例以提供附加功能或建構程序來滿足您的特定需求。

範例數據

若要使用本文中的宏,請在工作表中輸入下列範例數據:

A1: a B1: 1
A2: b B2: 2
A3: x B3: 3
A4: x B4: 4
A5: c B5: 5
A6: x B6: 6
A7: d B7: 7
A8: x B8: 8
A9: x B9: 9
A10: e B10: 10

範例宏

在新的宏模組中,輸入下列宏。

Sub DeleteCells()

     'Loop through cells A1:A10 and delete cells that contain an "x."
     For Each c in Range("A1:A10")
        If c = "x" Then c.EntireRow.Delete
    Next

End Sub

Excel 2002 和更新版本 Excel 中範例宏的行為

當您在 Excel 2002 和更新版本的 Excel 中執行 DeleteCells 宏時,只會刪除數據列 3、6 和 8。 雖然數據列 4 和 9 在資料行 A 中包含 「x」,但宏不會刪除數據列。 宏的結果如下:

A1: a B1: 1
A2: b B2: 2
A3: x B3: 4
A4: c B4: 5
A5: d B5: 7
A6: x B6: 9
A7: e B7: 10

當 Microsoft Excel 刪除第 3 列時,所有儲存格都會向上移動一列。 例如,單元格 A3 假設儲存格 A4 的內容,單元格 A4 會假設儲存格 A5 的內容,依此類推。 在 [For Each] 之後...下一個迴圈會評估單元格,它會評估下一個單元格;因此,當儲存格移動時,迴圈可能會略過它們。

Microsoft Excel 5.0 和 Microsoft Excel 7.0 中範例宏的行為

當您在 Excel 5.0 和 Excel 7.0 中執行 DeleteCells 宏時,宏會刪除包含 「x」 的所有數據列。宏的結果如下:

A1: a B1: 1
A2: b B2: 2
A3: c B3: 5
A4: d B4: 7
A5: e B5: 10

刪除第 3 列時,所有儲存格都會向上移動一列。 然後,單元格 A3 會假設單元格 A4 的內容,單元格 A4 會假設儲存格 A5 的內容,依此類推。

不過,不同於 Excel 2002 和更新版本 Excel 中循環的行為,當 「For Each...Next“ 循環會評估 Excel 5.0 和 Excel 7.0 中的儲存格,如果在迴圈中刪除儲存格,迴圈會重新評估單元格。 因此,不會略過單元格。

當您要使用循環刪除儲存格時,請使用下列宏:

Sub DeleteCells2()

     Dim rng As Range
     Dim i As Integer, counter As Integer
    
     'Set the range to evaluate to rng.
     Set rng = Range("A1:A10")
    
     'initialize i to 1
     i = 1
    
     'Loop for a count of 1 to the number of rows
     'in the range that you want to evaluate.
     For counter = 1 To rng.Rows.Count
    
          'If cell i in the range contains an "x",
           'delete the row.
           'Else increment i
            If rng.Cells(i) = "x" Then
                rng.Cells(i).EntireRow.Delete
            Else
                i = i + 1
            End If
    
     Next

End Sub

此宏在所有 Excel 版本中的結果如下:

A1: a B1: 1
A2: b B2: 2
A3: c B3: 5
A4: d B4: 7
A5: e B5: 10

使用循環刪除儲存格的其他方法

這是上述方法的替代方法。 這個方法會產生相同的結果。

 Sub DeleteCells3()

     Dim rng As Range, i As Integer

     'Set the range to evaluate to rng.
     Set rng = Range("A1:A10")

     'Loop backwards through the rows
     'in the range that you want to evaluate.
     For i = rng.Rows.Count To 1 Step -1
    
             'If cell i in the range contains an "x", delete the entire row.
             If rng.Cells(i).Value = "x" Then rng.Cells(i).EntireRow.Delete
     Next

End Sub