如果在某个范围内找到单个单元格值,则删除整行

时间:2013-10-07 20:40:50

标签: excel vba excel-vba

我正在处理每个多站记录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

非常感谢任何帮助或其他方式来处理这个问题!

1 个答案:

答案 0 :(得分:0)

This Question

的答案的修改版本
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

注意: 如果您的数据有标题,请运行此代码,如果不提供建议。

记住 在您确信数据正常工作之前,请始终在数据副本上运行任何代码而不是实际数据。