VBA循环遍历列将每个单元格与variables进行比较,如果不匹配,则删除该行

我目前正在尝试创build一个循环,将从第5行开始查看C列,并比较该列中的每个单元格,直到它到达该列中最后一个使用的单元格。 每个单元格将检查8个variables,看看是否匹配。 如果单元格不匹配任何variables,则必须删除整行。

我目前的尝试看起来像:

Dim AC as long Dim LastRow as long AC=5 LastRow= Activesheet.range("A" & Rows.count).end(xlup).row For AC = 5 To LastRow With Cells(AC, "C") Do Until Cells(AC, "C").Text = OC1 Or Cells(AC, "C").Text = OC2 Or Cells(AC, "C").Text = OC3 Or Cells(AC, "C").Text = OC4 Or Cells(AC, "C").Text = NC1 Or Cells(AC, "C").Text = NC2 Or Cells(AC, "C").Text = NC3 Or Cells(AC, "C").Text = NC4 Rows(AC).EntireRow.Delete Loop End With Next AC 

这应该保证,一旦一行被删除,新的行占据了它的位置(例如,删除整行第5行将导致第6行成为第5行)所以它应该退出Do循环时,有一个匹配,抓下一个行号和重复,直到有另一场比赛。 只有代码一直抛出执行中断的错误。 有人能告诉我我做错了什么吗?

如果您的代码导致无限循环,并且仅当您尝试查杀无限循环时才会生成错误,则可以使用以下代码:

 Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim AC As Long Dim LastRow As Long AC = 5 LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row Do While AC <= LastRow If Cells(AC, "C").Text <> OC1 And _ Cells(AC, "C").Text <> OC2 And _ Cells(AC, "C").Text <> OC3 And _ Cells(AC, "C").Text <> OC4 And _ Cells(AC, "C").Text <> NC1 And _ Cells(AC, "C").Text <> NC2 And _ Cells(AC, "C").Text <> NC3 And _ Cells(AC, "C").Text <> NC4 Then Rows(AC).Delete LastRow = LastRow - 1 Else AC = AC + 1 End If Loop Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic 

你现在正在做的事情的问题是,一旦你靠近LastRow (假设你已经删除了任何先前的行),你正在查看空白行,因此无限删除它们。


或者,当然,您可以使用更普遍接受的删除行的方式 – 即从底部开始并向上工作:

 Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim AC As Long Dim LastRow As Long LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row For AC = LastRow To 5 Step -1 If Cells(AC, "C").Text <> OC1 And _ Cells(AC, "C").Text <> OC2 And _ Cells(AC, "C").Text <> OC3 And _ Cells(AC, "C").Text <> OC4 And _ Cells(AC, "C").Text <> NC1 And _ Cells(AC, "C").Text <> NC2 And _ Cells(AC, "C").Text <> NC3 And _ Cells(AC, "C").Text <> NC4 Then Rows(AC).Delete End If Next Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic