简体   繁体   中英

How to clear cell contents in VBA if they are within a range of numeric values

I'm trying to clear the contents of any cells within a column that contain the numbers 1-12. I'm currently using a for loop and an if statement, going one at a time through the numbers 1-12 and clearing the contents if the cell contains those values. The file I'm working with has over 35,000 rows of data; is there a more efficient way to tell the macro to delete those numbers without creating an individual elseif statement for them?

For r = 2 To i
    If Cells(r, 1).Value = "1" Then
        Cells(r, 1).ClearContents
        ElseIf Cells(r, 1).Value = "2" Then
        Cells(r, 1).ClearContents

You can use comparison operators combined with an And:

For r = 2 to i
    If Cells(r, 1).Value >= 1 And Cells(r, 1).Value <= 12 Then
        Cells(r, 1).ClearContents
    End If
Next

Use a filter:

Sub tgr()

    Dim ws As Worksheet
    Set ws = ActiveWorkbook.ActiveSheet

    With Application
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    With ws.Range("A1", ws.Cells(ws.Rows.Count, "A").End(xlUp))
        .AutoFilter 1, ">=1", xlAnd, "<=12"
        .Offset(1).ClearContents
        .AutoFilter
    End With

    With Application
        .Calculation = xlCalculationAutomatic
        .ScreenUpdating = True
        .EnableEvents = True
    End With

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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