如何有效地执行选择和并集的交集?

How do I perform an intersect of a selection and a union effectively?

我正在编写一个代码,只要该选择完全包含在范围并集内,就会用一种颜色填充用户选择。

If Not Application.Intersect(Selection, Union(Range("B4:X23"), Range("Z4:AH23"), _
                              Range("B25:X32"), Range("Z25:AH32"),Range("B34:X44"),  _
                              Range("Z34:AH44"))) Is Nothing Then   
    Selection.Interior.ColorIndex = modButtons.intColour   
End If

对单个范围多次执行此行不是一种选择,因为在我的实际代码中有 30 个范围集。

所以问题是,当活动单元格在范围之外时它不会填充选区中的单元格,但如果活动单元格在范围内,它会填充选区中超出范围的单元格.

这取决于您要实现的目标。

如果在部分重叠的情况下您只想填充选择的相交范围,请使用:

Dim rngIntersect As Range 
Set rngIntersect = Intersect(Selection, Union(Range("B4:X23"), Range("Z4:AH23"), _
                              Range("B25:X32"), Range("Z25:AH32"), Range("B34:X44"), _
                              Range("Z34:AH44")))

If Not rngIntersect Is Nothing Then
    rngIntersect.Interior.ColorIndex = modButtons.intColour 
End If

如果您只想填充完全相交的选区,请使用:

Dim rngIntersect As Range 
Set rngIntersect = Intersect(Selection, Union(Range("B4:X23"), Range("Z4:AH23"), _
                              Range("B25:X32"), Range("Z25:AH32"), Range("B34:X44"), _
                              Range("Z34:AH44")))

If Not rngIntersect Is Nothing And rngIntersect.Cells.Count = Selection.Cells.Count Then
    Selection.Interior.ColorIndex = modButtons.intColour 
End If