[英]Iterate through cells in a range
目前,我正在使用以下代碼檢查特定范圍的單元格中的列A是否為#N / A值,如果找到,我將刪除該行。
With Sheets(Sheet)
For LRow = 45 To 29 Step -1
With .Cells(LRow, "A")
If (CVErr(.Value) = CVErr(xlErrNA)) Then .EntireRow.Delete
End With
Next LRow
End With
我需要擴展這個,所以我檢查所有列1到10,而不是只是A.我嘗試了這個小修改(嵌套另一個循環),但它不起作用。 有什么建議?
With Sheets(Sheet)
For LRow = 45 To 29 Step -1
For LCol = 10 To 1 Step -1
With .Cells(LRow, LCol)
If (CVErr(.Value) = CVErr(xlErrNA)) Then .EntireRow.Delete
End With
Next LCol
Next LRow
End With
這里有兩個問題:
嵌套的
一旦發現N / A,在任何給定的行上,你需要中止循環
嘗試
Set sh = Sheets(Sheet)
For LRow = 45 To 29 Step -1
For LCol = 10 To 1 Step -1
If (CVErr(sh.Cells(LRow, LCol).Value) = CVErr(xlErrNA)) Then
sh.Cells(LRow, 1).EntireRow.Delete
Exit For ' Exit the LCol loop
End If
Next LCol
Next LRow
這可能會因英語以外的語言而失敗
Sub DeleteNA()
Dim rRange As Range
Dim rFound As Range
Const sNA As String = "#N/A"
Do
Set rRange = Sheet1.Range("A29:F49")
Set rFound = rRange.Find(sNA, , xlValues, xlWhole, xlByRows)
If Not rFound Is Nothing Then
rFound.EntireRow.Delete
Else
Exit Do
End If
Loop
End Sub
更改A29:F49以適合您的數據。
您可以采取略微不同的方法
Sheets("Sheet1").Select
Set cols = Range("A1:D80")
For Each Cell In cols
If Cell.Value = "XXX" Then
Cell.EntireRow.Delete
End If
Next
我相信您使用的嵌套'with'子句存在問題。
您可以定義一個適當的范圍並使用'for each'循環,這將使事情更清晰,更容易閱讀。 為測試目的,我將范圍命名為“MyRange”。
Sub test()
Dim cell As Excel.Range
For Each cell In [myRange]
If CVErr(cell.Value) = CVErr(xlErrNA) Then cell.EntireRow.Delete
Next cell
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.