【发布时间】:2021-05-27 09:29:10
【问题描述】:
如果 Excel 中的行早于所选日期,我有一些代码会删除它们。该函数有效,但不会删除最后一个值。
例如,如果我运行此代码:
Dim count As Long
count = 0
Dim searchRng As Range: Set searchRng = Range("Q9:Q5000")
Dim Cell As Range
For Each Cell In searchRng
If ((Cell.Value < CDate(TextBoxDelete.Value)) And (Cell.Value <> "")) Then
count = count + 1
Debug.Print ("Cell " & count & ": " & Cell.Value & " txtbox: " & TextBoxDelete.Value)
'Cell.EntireRow.Delete ' This line deletes the Row
End If
Next Cell
如果我运行此代码,我会得到以下输出:
Cell 1: 03.03.2021 txtbox: 04.03.2021
Cell 2: 03.03.2021 txtbox: 04.03.2021
Cell 3: 03.03.2021 txtbox: 04.03.2021
Cell 4: 03.03.2021 txtbox: 04.03.2021
这是正确的,这些是比 TextBox.Value 更早的 4 个单元格
现在,当我使用相同的函数并在 DELETE 部分中添加注释时,输出如下所示:
Cell 1: 03.03.2021 txtbox: 04.03.2021
Cell 2: 03.03.2021 txtbox: 04.03.2021
代码是相同的,但你可以看到它现在只找到 2 个值 - 而不是 4 个!
找到的 2 个单元格被删除,但其他 2 个单元格没有被删除。
有没有人遇到过类似的行为?
编辑:在回答部分的所有帮助之后,我想出了这个:
For j = searchRng.count To 1 Step -1
If ((searchRng(j).Value < CDate(TextBoxDelete.Value)) And (searchRng(j).Value <> "")) Then
count = count + 1
Debug.Print ("Cell " & count & ": " & searchRng(j).Value & " txtbox: " & TextBoxDelete.Value)
searchRng(j).EntireRow.Delete ' Delete Call for the Row
End If
Next j
这是有效的代码还是有任何缺陷?运行它正是我需要的。
【问题讨论】:
-
这是一个常见问题。您正在删除要迭代的范围内的行。这意味着 for each 会混淆。您需要更改循环设计,以便向后迭代,以便删除不会影响即将发生的事情您可以通过使用常规的 for next 循环来做到这一点,例如对于 myItem = myItems.count 到 1 步 -1 等
-
那么在我的情况下你会如何修改它?我们可以为 searchRange.Count -1 中的每个单元格做些什么吗?
-
这能回答你的问题吗? VBA Excel delete rows with specific value
-
这个问题已经很常见了。检查两个答案