简体   繁体   中英

Excel VBA Delete Row If Misspelled Word

I am trying to delete the entire row, if a cell contains a misspelled word. If a row is removed, is skips a row, thus missing any misspelled words that may occur directly after another.

Here is the code:

Sub DeleteMispelledCells()
For Each cl In ActiveSheet.UsedRange
If Not Application.CheckSpelling(Word:=cl.Text) Then _
cl.EntireRow.Delete
Next cl
End Sub

I understand the issue is the cl is not taking into account that the current row was removed, but I do not know how to correct this. I am also aware that if the loop ran from the last row to the first, instead of the first to the last, that it would also be corrected. However, I do not know how to do this either.

In order to loop through every row in reverse order you'll do something like this:

Sub DeleteMispelledCells()
  Dim lRow As Long, cl As Range

  With ActiveSheet
    For lRow = .UsedRange.Rows.Count To 1 Step -1
      For Each cl In .Rows(lRow)
        If Not IsEmpty(cl) Then
          If Not Application.CheckSpelling(Word:=cl.Text) Then
            cl.EntireRow.Delete
            Exit For
          End If
        End If
      Next cl
    Next lRow
  End With
End Sub

I am not 100 % sure I've gotten all of the syntax right, as I am not on a computer at which I can test it, but it should at least give you somewhere to start.

This is a classic problem in this kind of loop-controlled logic (in any programming language). If you are iterating through, say, 5 rows ("#1..5"), and you delete the first row, then ... there are now 4 rows and what used to be row #2 is now row #1 and what used to be row #3 is now #2. So, the loop proceeds to "row #2" and guess what: you just skipped over "the former row #2," now in position #1.

Looping through the list backwards, as shown earlier, is one good way to compensate.

Another way, and one that I personally prefer, is to first loop through the items, flagging the ones that you decide you want to delete (eg by setting a flag-value in another column). Then, in a separate (backwards) loop, actually delete the flagged items. This will make it a lot easier for you to properly debug the logic that checks for those misepeled wurds. ;-) First decide what you want to do, then go back and do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM