如何find一个范围是否包含在另一个范围内? VBA

我有一个比较两个范围的问题。 为了简单起见,我将采取两个简单的范围M6:M10M6:M8 ,我想知道第二个是否包含在第一个中,而我要写的第一个东西

  Sub example() Dim range1, range2, inte As range Set range1 = range("M6:M10") Set range2 = range("M6:M8") Set intersec = Intersect(range1, range2) If intersec = range2 Then [if statement] End If End Sub 

但是这个过程返回给我下面的错误:

PRB: Error 13 (Type Mismatch) & Error 3061 w/ SQL Queries

所以,也许我不能用这种方法“相交”…任何提示如何testing范围的包含? 非常感谢你!

这是一个方法:

 Sub ProperSubSet() Dim range1 As Range, range2 As Range, inte As Range Dim r As Range Set range1 = Range("M6:M10") Set range2 = Range("M6:M8") For Each r In range2 If Intersect(r, range1) Is Nothing Then MsgBox "range2 is not a proper subset of range1" Exit Sub End If Next r MsgBox "range2 is a proper subset of range1" End Sub 

我使用的方式是这样的:

 If Application.Intersect(rng1, rng2) Is Nothing Then 'herecomesthecode Else 'herecomesthecode End if 

您可以删除其他或写不是没有,取决于你想要达到什么。

这里是你可以尝试的东西:

 Sub Test() Dim R1 As Range, R2 As Range, R3 As Range Set R1 = Application.InputBox("Select first range", , , , , , , 8) Set R2 = Application.InputBox("Select second range", , , , , , , 8) Set R3 = Intersect(R1, R2) If Not R3 Is Nothing Then If R3.Address = R1.Address Then MsgBox "First Range is subset of second" ElseIf R3.Address = R2.Address Then MsgBox "Second Range is subset of first" Else MsgBox "Neither range contained in the other" End If Else MsgBox "Ranges are disjoint" End If End Sub 

首先,将范围1和范围2variables声明为范围。

然后,当您将intersecvariables与range2variables进行比较时,请使用range方法的address属性来比较内容。

就像是:

 Sub example() Dim range1 As Range, range2 As Range, intersec As Range Set range1 = Range("M6:M10") Set range2 = Range("M11:M12") Set intersec = Intersect(range1, range2) If Not intersec Is Nothing Then If intersec.Address = range2.Address Then '[CODE GOES HERE] End If End If End Sub 

另一个附加变体:

 Sub ProperSubSet2() Dim range1 As Range, range2 As Range Set range1 = [M6:M10] Set range2 = [M6:M8] Set rComp = Intersect(range2, range1) If Not rComp Is Nothing Then If rComp.Cells.Count = range2.Cells.Count Then MsgBox "range2 is a proper subset of range1" Else MsgBox "range2 is not a proper subset of range1" End If Else MsgBox "Both ranges aren't intersected at all!" End If End Sub 

您可以将交叉点与范围进行比较,以确定一个范围是否包含在另一个范围内。 一些代码来显示这个…

 Sub TestExample() Dim Range1 As Range: Set Range1 = Range("M6:M10") Dim Range2 As Range: Set Range2 = Range("M6:M8") MsgBox Example(Range1, Range2) End Sub Function Example(Range1 As Range, Range2 As Range) As Integer Dim Overlay As Range: Set Overlay = Application.Intersect(Range1, Range2) If Not Overlay Is Nothing Then If Overlay.Address = Range1.Address Then Example = Example + 1 If Overlay.Address = Range2.Address Then Example = Example + 2 End If End Function 

如果没有范围完全包含在另一个范围内,函数将返回0;如果第一个范围包含在第二个范围内,则返回1;如果第二个范围包含在第一个范围内,则返回2;如果范围相等,则返回3