比较日期与组合框检测&删除特定日期范围之间的行

时间:2017-03-15 05:00:02

标签: excel-vba vba excel

This is my excel sheet where I am working to get data only between a specific date range selected through two combo boxes.

你好,

感谢您最近的支持。我正在使用excel表(图像附在此处),这里我有大约60k行,在A栏中重复相同的日期。实际上我需要做的是选择开始日期&通过用户表单结束日期(可以在图片中看到)。何时单击“确定”按钮应删除具有超出给定日期范围的日期的休息行。 但是我的代码并没有完全符合我的要求。删除范围内的一些行。我接受可能有我的错误,但经过这么多的努力,我无法找到答案。并且组合框中的日期重复了这么多次&没有排序。请仔细阅读下面的代码 -

Private Sub CancelButton_Click()
Unload UserForm1
End Sub

Private Sub ComboBox1_Change()
ComboBox1.Value = Format(ComboBox1.Value, "dd-mmm-yyyy")
End Sub

Private Sub ComboBox2_Change()
ComboBox2.Value = Format(ComboBox2.Value, "dd-mmm-yyyy")
End Sub

Private Sub okButton_Click()
Dim i As Double, dt1 As String, dtt1 As String
Dim dt2 As String, dtt2 As String
Dim ws As Worksheet, lRow As Long
Set ws = ActiveWorkbook.Sheets(1)
With ws
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
End With
dt1 = ComboBox1.Value
dtt1 = CDate(dt1)
dt2 = ComboBox2.Value
dtt2 = CDate(dt2)
Application.ScreenUpdating = False
For i = 2 To lRow
If Range("A" & i).Value >= dtt1 And Range("A" & i).Value <= dtt2 Then
     Rows(i).Select
     Selection.Delete
     i = i - 1
End If
Next
Application.ScreenUpdating = True
Unload UserForm1
End Sub

Private Sub UserForm_Initialize()
Set ws = ActiveWorkbook.Sheets(1)
With ws
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
End With
ComboBox1.RowSource = "A2:A" & lRow
ComboBox2.RowSource = "A2:A" & lRow
End Sub

提前多多感谢。

1 个答案:

答案 0 :(得分:2)

而不是

For i = 2 To lRow

For i = lRow To 2 step -1

请注意:我没有检查你的其余代码,因为这可能是问题所在;当您想要通过VBA删除电子表格中的行(或列)时,从下到上(或者如果您正在处理列的情况下从右到左)执行它总是一个很好的过程。