You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在含And的IF语句中忽略空白单元格的VBA脚本优化需求

Fixing Your VBA Script to Ignore Rows with Blank Cells in Columns C-F

Got it, the issue with your original script is that it doesn’t account for blank cells in columns C, D, E, or F—right now, if any of those cells are blank, the >=10 comparison might behave unexpectedly (or delete rows you don’t intend to). We need to add checks to ensure all four cells have actual values before verifying they’re all ≥10.

Here’s the updated script that handles blank cells properly:

Sub test()
    Dim i As Long
    ' Traverse from the last row up to avoid skipping rows after deletion
    For i = Cells(Rows.Count, "A").End(xlUp).Row To 2 Step -1
        ' First check that none of C-F are blank, then verify all values are ≥10
        If Not IsEmpty(Cells(i, "C").Value2) And _
           Not IsEmpty(Cells(i, "D").Value2) And _
           Not IsEmpty(Cells(i, "E").Value2) And _
           Not IsEmpty(Cells(i, "F").Value2) And _
           Cells(i, "C").Value2 >= 10 And _
           Cells(i, "D").Value2 >= 10 And _
           Cells(i, "E").Value2 >= 10 And _
           Cells(i, "F").Value2 >= 10 Then
            Rows(i).Delete
        End If
    Next i
End Sub

Key Changes Explained:

  • We added Not IsEmpty(...) checks for each column: this ensures we only evaluate rows where all four cells have real values (not blank). If any cell in C-F is empty, the condition fails, and we skip deleting that row.
  • The underscores _ split the long condition across multiple lines for readability—VBA treats this as a single line of code.

Bonus: Handling "Fake Blanks" (Cells with Spaces)

If your sheet has cells that look blank but contain spaces or invisible characters, replace Not IsEmpty(...) with Len(Trim(Cells(i, "X").Value2)) > 0 to catch those cases. Here’s that version:

Sub testWithFakeBlanks()
    Dim i As Long
    For i = Cells(Rows.Count, "A").End(xlUp).Row To 2 Step -1
        If Len(Trim(Cells(i, "C").Value2)) > 0 And _
           Len(Trim(Cells(i, "D").Value2)) > 0 And _
           Len(Trim(Cells(i, "E").Value2)) > 0 And _
           Len(Trim(Cells(i, "F").Value2)) > 0 And _
           Cells(i, "C").Value2 >= 10 And _
           Cells(i, "D").Value2 >= 10 And _
           Cells(i, "E").Value2 >= 10 And _
           Cells(i, "F").Value2 >= 10 Then
            Rows(i).Delete
        End If
    Next i
End Sub

Trim() removes leading/trailing spaces, and Len() checks if there’s any remaining content—this ensures cells with only spaces are treated as "blank" and skipped.

内容的提问来源于stack exchange,提问作者Fabricio Martinez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:49:26