1

我正在处理每个站点记录 31 天数据的每日数据,我需要一个 VBA 代码来删除闰年日。我有一个记录的数据日期列表和一个我想删除的不是闰年的年份列表。为了删除额外的 30 天和 31 天,我使用了以下基本代码:

Dim lastrow, i As Long

lastrow = ActiveSheet.Cells(65536, 1).End(xlUp).Row

For i = 1 To lastrow
    'delete 31st days for February
    If ActiveSheet.Range("D" & i) = 2 And ActiveSheet.Range("E" & i) = 31 Then
        Rows(i).Select
        Selection.Delete shift:=xlUp
    End If
Next i

非常简单而且效果很好,所以我希望能够做类似的事情,在数据中找到不存在的日期(即 02/29/非闰年)并删除该行,但事实证明它非常很难匹配一个范围内的值。我在想这样的事情:

Dim lastrow, i As Long, leapyear as Workbook

Set leapyear = Workbooks("LeapYears.xlsx")

lastrow = ActiveSheet.Cells(65536, 1).End(xlUp).Row

For i = 1 To lastrow
    'obviously this is where I have the problem trying to match a cell to a range
    If ActiveSheet.Range("D" & i) = leapyear.Sheets(1)range("C2:C90") Then
        Rows(i).Select
        Selection.Delete shift:=xlUp
    End If
Next i

非常感谢任何帮助或其他处理方式!

4

1 回答 1

0

我对这个问题的回答的修改版

Sub Sample()

Dim StartingScreenUpdateValue As Boolean
Dim StartingEventsValue As Boolean
Dim StartingCalculations As XlCalculation

With Application
    StartingScreenUpdateValue = .ScreenUpdating
    StartingEventsValue = .EnableEvents
    StartingCalculations = .Calculation
    .ScreenUpdating = False
    .EnableEvents = False
    .Calculation = xlCalculationManual
End With


Dim varTestValues As Variant

varTestValues = Workbooks("LeapYears.xlsx").Sheets(1).Range("C2:C90")

Rows(1).Insert
[A1].FormulaR1C1 = "TempHeader1"
[A1].AutoFill Destination:=Range("A1:H1"), Type:=xlFillDefault

Range("D1").AutoFilter Field:=4, Criteria1:=Application.Transpose(varTestValues), Operator:=xlFilterValues

Range("D2", Range("D" & Rows.Count).End(xlUp)) _
    .SpecialCells(xlCellTypeVisible).EntireRow.Delete

ActiveSheet.AutoFilterMode = False
Rows(1).Delete


With Application
    .ScreenUpdating = StartingScreenUpdateValue
    .EnableEvents = StartingEventsValue
    .Calculation = StartingCalculations
End With

End Sub

注意:此代码运行假设您的数据有标题,如果没有请告知。

请记住,始终在您的数据副本上运行任何代码,而不是在您的实际数据上运行,直到您确信它可以 100% 运行。

于 2013-10-07T20:56:06.177 回答