首页 > 解决方案 > VBA OR IF 语句

问题描述

我想使用 OR 运算符,以便我的函数显示“如果单元格不以 'rw-promo' 或 'rw-content' 开头,则删除整行。

但是,该功能没有考虑“rw-content”,所以我留下了以“rw-promo”开头的单元格。

任何帮助表示赞赏!


Sub monthly_delete_emails()

    'Disab;e certain Excel features, whilst the macro is running'
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False
    Application.ScreenUpdating = False

        'Declare variables'
        Dim deleteRow As Long
        Dim ws As Worksheet

        'Set objects'
        Set ws = ActiveSheet

         'Loop through the rows of data, in order to delete rows with'
         'a value in column B. Our macro starts at row 9'
         For deleteRow = ws.Range("B" & Rows.Count).End(xlUp).Row To 9 Step -1

             'identify values in col B, which start with ___'
             If Not ws.Range("B" & deleteRow).Value Like "rw-promo*" Or ws.Range("B" & deleteRow).Value Like "rw-content*" Then
                 Rows(deleteRow).EntireRow.delete
             End If

         'Move to next cell in the range, which is being looped'
         Next deleteRow

    'Re-enable the above Excel features, which were disables whilst the macro ran'
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True
    Application.ScreenUpdating = True

End Sub

标签: excelvba

解决方案


问题是 'Not' 运算符不适用于您的两个语句。它以英语语句的方式显示,但不以 VBA 条件的方式执行。您发布的代码的意思是:“如果单元格不以 rw-Promo 开头,或者如果单元格以 rw-content 开头,请删除该单元格”。您需要阅读该行:

If Not ws.Range("B" & deleteRow).Value Like "rw-promo*" Or Not ws.Range("B" & deleteRow).Value Like "rw-content*" Then

同样的事情会让人们在任何编程语言中都感到困惑。


推荐阅读