我正在尝试使用工作表中的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中没有任何数据的行,但我不确定如何遍历行和列。我已经看到很多关于循环列的说明,但是我找不到任何关于如何在二维中循环检查单元格中的数据。
由于
答案 0 :(得分: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
答案 1 :(得分: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
将三个检查连接在一起。在更复杂的情况下,在Adam Bernier的答案中嵌套的For
循环会更好