简体   繁体   English

如果它们在数值范围内,如何清除VBA中的单元格内容

[英]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. 我正在尝试清除包含数字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. 我目前正在使用for循环和if语句,一次遍历数字1-12,如果单元格包含这些值,则清除内容。 The file I'm working with has over 35,000 rows of data; 我正在使用的文件具有35,000多行数据; is there a more efficient way to tell the macro to delete those numbers without creating an individual elseif statement for them? 有没有一种更有效的方法来告诉宏删除这些数字而不为它们创建单独的elseif语句?

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: 您可以将比较运算符与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

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

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