简体   繁体   English

需要代码来删除基于值的行(VBA)

[英]Need code to delete rows based on value (VBA)

What I'm trying to do is get this code to delete rows based on the date in Column B. If the date in column B falls within the last 3 days, it should get deleted. 我要做的是获取此代码以根据B列中的日期删除行。如果B列中的日期属于最近3天,则应删除它。 The code seems to delete 1 or 2 rows, but not all rows with 'bad' dates. 代码似乎删除1或2行,但不是所有具有“错误”日期的行。

I have tried setting the formatting of all columns to General. 我已尝试将所有列的格式设置为常规。 The formatting is fine so that's not the issue. 格式化很好,所以这不是问题。 I converted the dates to numbers so I could get the last 3 days and not run into error. 我将日期转换为数字,以便我可以获得最后3天而不会遇到错误。 It should be known that this data is starting as a .csv file and is being saved as an excel file earlier in the code. 应该知道此数据以.csv文件开头,并在代码中保存为excel文件。

Dim myrow As Long
Dim mydate As Long

mydate = Int(CDbl(Now()))
mydate = mydate - 3

Columns("B:B").NumberFormat = "0"

Application.CutCopyMode = False

MsgBox "Last row with data:" & Cells(Rows.Count, "B").End(xlUp).row

For myrow = 1 To Cells(Rows.Count, "B").End(xlUp).row Step 1

        If Range("B" & myrow).value = mydate + 1 Or Range("B" & myrow).value = mydate + 2 Or Range("B" & myrow).value = mydate + 3 Then
        Range("B" & myrow).EntireRow.Delete
        End If

Next myrow

I expect this code to delete all rows which contain any of the last 3 days in Column B. Column B is a set of dates formatted as "43588" "43599" etc. However, it is only deleting 1 or 2 rows when the code runs. 我希望此代码删除包含B列中最后3天中任何一行的所有行.B列是一组格式为“43588”“43599”等的日期。但是,它只删除1或2行代码运行。 I have a message box which tells the last row with data, and it is showing correct values, meaning "Cells(Rows.Count, "B").End(xlUp).row" works fine. 我有一个消息框告诉最后一行有数据,它显示正确的值,意思是“Cells(Rows.Count,”B“)。End(xlUp).row”工作正常。

I appreciate any help. 我感谢任何帮助。

When deleting rows in a loop, you must iterate through the rows in reverse order (bottom-to-top). 删除循环中的行时,必须以相反的顺序(从下到上)遍历行。 Otherwise, when you delete a row, the rows below it are renumbered and might be skipped. 否则,当您删除行时,它下面的行将重新编号,可能会被跳过。

For myrow = Cells(Rows.Count, "B").End(xlUp).row to 1 Step -1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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