【问题标题】:VBA loop through column to compare each cell with variable and delete the row if it doesn't matchVBA遍历列以将每个单元格与变量进行比较,如果不匹配则删除该行
【发布时间】:2017-04-21 07:10:13
【问题描述】:

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

我目前的尝试是这样的:

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 Loop,抓住下一个行号并重复,直到有另一个匹配。只有代码不断抛出执行中断错误。有人可以告诉我我做错了什么吗?

【问题讨论】:

  • 真的会产生错误,还是进入死循环?

标签: vba excel


【解决方案1】:

如果您的代码导致了无限循环,并且您的错误仅在您尝试终止无限循环时产生,您可以使用以下代码:

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

【讨论】:

  • LastRow 应该计算最后使用的行而不是工作表,我相信?它也立即出错,当我单步执行时,它仍然在第一行(第 5 行)
  • LastRow 被计算为包含 A 列中最后一个非空单元格的行。代码生成了什么错误? (它对我有用,但可能是我的测试数据和您的实际数据之间存在差异导致它出现问题。)
  • 我把我的代码换成了你的,现在它似乎可以工作了。它必须经过大量的数据,所以它必须运行一段时间。与我的代码相比,您的代码非常干净,但我仍然觉得我的代码应该成功了……这不明白为什么比我的代码不工作更困扰我哈哈
  • Nope...它一直到最后一行是 133088,然后抛出与之前相同的错误:代码执行已被中断
  • 这个帖子和答案可能有用:stackoverflow.com/questions/2154699/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 2022-09-06
  • 1970-01-01
  • 2019-06-28
  • 1970-01-01
  • 2022-01-02
相关资源
最近更新 更多