一个VBA For循环中的多个范围?

D. *_*. R 3 excel vba for-loop excel-vba

我是VBA的初学者,我只想突出N列和AA列中的空单元格.可以在一个For循环中使用多个范围来实现此功能而不是以下代码吗?

Private Sub CommandButton22_Click()
    'HIGHLIGHT
    Dim cell As Range

    For Each cell In Range("N")
        If cell.Value = vbNullString Then
            cell.Interior.ColorIndex = 6
        End If
    Next cell

    For Each cell In Range("AA")
        If cell.Value = vbNullString Then
            cell.Interior.ColorIndex = 6
        End If

    Next cell
End Sub
Run Code Online (Sandbox Code Playgroud)

use*_*756 7

编辑加入SpecialCells方法,受益UsedRange于Thomas Inzina解决方案所指出的

使用对象的SpecialCells()方法,Range避免循环

Private Sub CommandButton22_Click()
    'HIGHLIGHT
    Intersect(Union(Range("N:N"), Range("AA:AA")), ActiveSheet.UsedRange).SpecialCells(xlCellTypeBlanks).Interior.ColorIndex = 6
End Sub
Run Code Online (Sandbox Code Playgroud)


小智 3

您可以通过组合两个范围地址来简单地创建一个非连续范围,如下所示:

For Each cell In Range("N:N,AA:AA")

Next
Run Code Online (Sandbox Code Playgroud)

但使用 Intersect 方法将范围修剪到工作表的已使用部分会更有效:

For Each cell In Intersect(Range("N:N,AA:AA"), ActiveSheet.UsedRange)
    If cell.Value = vbNullString Then
        cell.Interior.ColorIndex = 6
    End If
Next
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

在此输入图像描述