簡體   English   中英

在二維VBA中循環遍歷Excel中的單元格

[英]Looping through cells in Excel in two dimensions VBA

我正在嘗試在工作表中使用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

我想擺脫EF和G列中沒有任何數據的行,但是我不確定如何遍歷行和列。 我已經看到了很多關於循環訪問一列的說明,但是我找不到關於如何在二維中循環檢查單元格以獲取數據的任何信息。

謝謝

遍歷行和列的基本思想是需要兩個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

這應該工作:

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循環會更好

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM