簡體   English   中英

我如何在VBA中編寫一個循環,如果一個范圍內的單元格及其旁邊的單元格都等於一個常數,它將刪除一行?

[英]How do I write a loop in VBA that will delete a row if a cell in a range and the cell next to it both equal a constant?

[這是在Excel 2007中]

換句話說,該循環將循環遍歷一個列范圍(rngAddressName)中的所有活動單元格,並且,如果范圍AND緊鄰其左側的單元格中包含字符串“#N / A”,則它將刪除該行。

不幸的是,我嘗試過的一切都沒有任何實際效果。 這是我最好的選擇:

i = 1
For counter = 1 To rngSC2A.Rows.Count
Contents = rngSC2A.Cells(i).Value
If Contents = "#N/A" Then
If rngAddressName.Cells(i).CellOffset(0, -1).Value = "#N/A" Then
rngAddressName.Cells(i).EntireRow.Delete
Else
End If
Else
i = i + 1
End If
Next

但這似乎找不到滿足條件的行(即使這些行存在於工作表中)。 我認為這可能與我正在查看Cell.Value中的事實有關,但我不確定。

您可以自動過濾范圍,刪除符合條件的所有行,然后關閉自動過濾功能。 這比循環更有效。

下面的示例適用於Sheet1中的A和B列。 修改變量以引用工作簿中的范圍和工作表。

Sub DeleteDoubleNA()
    Dim ws As Worksheet
    Dim rng As Range
    Dim lastRow As Long

    Set ws = ThisWorkbook.Sheets("Sheet1")

    lastRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row

    Set rng = ws.Range("A1:B" & lastRow)

    ' filter and delete all but header row
    With rng
        .AutoFilter field:=1, Criteria1:="#N/A"
        .AutoFilter field:=2, Criteria1:="#N/A"
        .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    End With

    ' turn off the filters
    ws.AutoFilterMode = False
End Sub

這與@Jon Crowell發布的出色答案截然不同。

如果使用Excel表,則可以使用表的ListObject獲取數據范圍,該范圍自動排除頁眉和頁腳行。

這樣避免了有時對最后一行進行錯誤的計算搜索。

您還希望清除數據上的所有現有過濾器,以免忽略任何行。

Dim myTable As Object
Set myTable = ActiveSheet.ListObjects(1) ' Works if worksheet contains only one table

' Clear pre-existing filters on the table
myTable.AutoFilter.ShowAllData

' Filter the table
With myTable.DataBodyRange
    .AutoFilter field:=1, Criteria1:="#N/A"
    .AutoFilter field:=2, Criteria1:="#N/A"
End With

' Delete visible cells in the filtered table
myTable.DataBodyRange.SpecialCells(xlCellTypeVisible).EntireRow.Delete

' Clear filters on the table
myTable.AutoFilter.ShowAllData

(1)ListObjects(1)是第一個(對我來說唯一的)工作表。 DataBodyRange引用該表的數據范圍,不包括頁眉和頁腳行。

暫無
暫無

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

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