Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if a range is included in another range using VBA?

I have a problem comparing two ranges. For simplicity I will take two simple ranges M6:M10 and M6:M8, I want to know if the second one is included into the first one and the first thing I though is to write

    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

But this procedure returns me the following error:

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

So maybe I can't use the method "intersect" in this way...any hint on how to test range's inclusion? Thank you very much!

like image 431
Bmb58 Avatar asked Apr 11 '16 11:04

Bmb58


People also ask

How do you check if a cell is within a range VBA?

Intersect(testRange, myRange) this checks if the range within the myRange variable overlaps or intersects with the range in the testRange variable. This function, the Intersect function, will return a range object where the two ranges overlap, or, if they don't overlap, it will return nothing.

How do you check if a particular value exists in column Excel VBA?

Example using VLOOKUP You can check if the values in column A exist in column B using VLOOKUP. Select cell C2 by clicking on it. Insert the formula in “=IF(ISERROR(VLOOKUP(A2,$B$2:$B$1001,1,FALSE)),FALSE,TRUE)” the formula bar. Press Enter to assign the formula to C2.

How do you reference a range in Excel VBA?

If the Excel VBA Range object you want to refer to is a single cell, the syntax is simply “Range(“Cell”)”. For example, if you want to make reference to a single cell, such as A1, type “Range(“A1″)”.


2 Answers

Here is one way:

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
like image 132
Gary's Student Avatar answered Sep 30 '22 11:09

Gary's Student


First, declare your range1 and range2 variables as ranges.

Then when you're comparing the intersec variable to the range2 variable, use the address property of the range method to compare the contents.

Something like:

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
like image 29
Harley B Avatar answered Sep 30 '22 10:09

Harley B