2009-12-03 109 views
2

我试图在工作表中使用VBA循环一组单元格,并检查它们是否包含任何数据。 我的表格是这样的:在Excel中循环遍历单元格VBA

__A_____B_____C_____D____E_____F____G 
1| 3122 -1 -1 3243 
2| -1 -1 -1 3243 1  1 1 
3| -1 -1 -1 3255   1 
5| 4232 2132 -1 3259 
6| 7544 1333 324 3259 
7| -1 -1 -1 3259 1  2 1 
8| -1 -1 -1 3259 1  1 1 
9| -1 -1 -1 3267 
10| 2121 222 -1 3267 

我想摆脱那些没有在E栏F和G的任何数据行,但我不知道如何通过行和列循环。我已经看到了许多关于循环列的说明,但我无法找到关于如何循环检查数据的单元格的任何内容。

感谢

回答

3

这应该工作:

Sub main() 

Dim maxRow As Integer 
Dim currentRow As Integer 

With Worksheets("Sheet1") 
    maxRow = .Range("A1").CurrentRegion.Rows.Count 

    Dim i As Integer 
    ' Start at the bottom and work upwards 
    For i = maxRow To 1 Step -1 
     ' 5 represents column E, 6 is column F and 7 is column G 
     If (.Cells(i, 5).Value = "" And .Cells(i, 6).Value = "" And _ 
      .Cells(i, 7).Value = "") Then 
      .Rows(i).Delete 
     End If 
    Next i 
End With 

End Sub 

因为只有三列检查,很容易只使用And三个检查连接在一起。在更复杂的情况下,嵌套的For循环,如Adam Bernier的回答将更好

+0

啊,你是对的。这种情况下的内部For循环是不必要的。 感谢您的回答:) – 2009-12-03 05:48:01

+1

您可以用一个只能进行一次评估的'WorksheetFunction.CountA'替换当前评估3件事情的If。这应该更快。 – Lunatik 2009-12-03 13:28:04

+0

我不知道该怎么做。这是我第一次真正使用任何的visual basic变体。 – 2009-12-03 19:29:09

4

遍历行和列的基本想法是,你需要两个for循环。

第一个遍历行,第二个遍历行。

我不使用VBA来记住行如何被删除,但是如果你向后循环(如下面的代码),你不应该失去跟踪你删除的行。

以下代码应该适合您的目的(尽管它要求重构!):
编辑:感谢barrowc进行更正。

Sub remove_some_rows() 
    Dim i As Long 
    Dim j As Long 

    Dim current_cell As Object 

    Dim beg_row As Long 
    Dim end_row As Long 
    Dim beg_col As Long 
    Dim end_col As Long 

    beg_row = 1 
    end_row = 10 
    beg_col = 1 
    end_col = 7 

    Dim empty_col_counter As Integer 

    For i = end_row To beg_row Step -1 

     empty_col_counter = 0 

     For j = end_col To beg_col Step -1 
      Set current_cell = ThisWorkbook.ActiveSheet.Cells(i, j) 

      If j > 4 And current_cell.Value = "" Then 
       empty_col_counter = empty_col_counter + 1 
      End If 
     Next j 

     If empty_col_counter = 3 Then 
      current_cell.EntireRow.Select 
      Selection.Delete 
     End If 

    Next i 
End Sub 
+0

+1,但合理使用With会有帮助,并且带有j的内部For循环每行重复检查相同的三个单元七次 – barrowc 2009-12-03 01:13:07

+0

@barrowc :感谢您的敏锐观察。我改写了更高效。 – bernie 2009-12-03 03:25:52