【发布时间】:2012-12-14 03:33:50
【问题描述】:
这是另一个我觉得有一个简单答案的问题,但我没有找到它。我正在遍历 D 列中的每个单元格并查找特定日期(来自用户输入),并根据该单元格的日期和一些相应单元格中的日期,更改行的颜色。
我希望能够将其删除,而不是为行着色。
这是我当前为这些行着色的代码:
Range(Cells(2, 4), Cells(Rows.Count, 4).End(xlUp)).Select
Dim rCell, otherCell As Range
Dim TheAnswer$
Dim ConvertedDate#
TheAnswer = InputBox("In M/D/YY format, enter the first day of the month for which this report is being run." & _
vbCr & vbCr & "For example, you would enter ""12/1/2012"" for the December 2012 report.", "Enter Date M/D/YY")
ConvertedDate = CDate(TheAnswer)
For Each rCell In Selection
If rCell.Value <> "" Then
If rCell.Value And rCell.Offset(, 5) < ConvertedDate And rCell.Offset(, 5) <> "" Then rCell.EntireRow.Interior.Color = RGB(255, 102, 0)
If rCell.Value < ConvertedDate And rCell.Offset(, 5) = "" Then
If rCell.Offset(, 6) < ConvertedDate And rCell.Offset(, 6) <> "" Then rCell.EntireRow.Interior.Color = RGB(255, 102, 0)
If rCell.Offset(, 7) < ConvertedDate And rCell.Offset(, 7) <> "" Then rCell.EntireRow.Interior.Color = RGB(255, 102, 0)
End If
End If
Next rCell
当我用 rCell.EntireRow.Delete 替换 rCell.EntireRow.Interior.Color = RGB(255, 102, 0) 时,我得到了错误。如果我单步执行代码,我可以看到它确实删除了第一行,但在下一行出现错误。
我显然有多个“If Then”语句,但是如果满足第一个“If Then”条件并且该行被删除,它应该移动到下一个单元格。在我看来,它仍在尝试检查已删除的行。我绝对不是 Excel VBA 专家,但我认为应该在 rCell.EntireRow.Delete 之后添加一些内容,告诉它移动到下一个单元格。我尝试添加Next rCell,但出现错误。 Exit For 完全停止宏。
【问题讨论】:
-
更详细地查看您的数据会很有用。删除行(手动或使用 VBA)的一种有效方法是在返回 TRUE 或 FALSE 的每一行上设置布尔 IF 测试,如果满足要删除的条件,则使用
Autofilter删除满足的条件。范围循环可能非常慢 -
我的电子表格没有什么特别之处。它基本上只是 D-K 列中的日期列表。我不熟悉
Autofilter,所以我想我必须调查一下。从我上面的代码中可以看出,我最初的方法是更改行颜色。我还想我也可以(或替代地)向其中一个单元格添加一些内容,然后删除单元格中包含该添加内容的所有行。