Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non intersect address in Range

Tags:

excel

vba

I have two ranges A2:E2 and B1:B5. Now if I perform intersect operation it will return me B2. I want some way through which I can get my output as B2 to be consider in any one range either A2:E2 and B1:B5. i.e if there is a repeated cell then it should be avoided.

Expected output :

A2,C2:E2,B1:B5

OR

A2:E2,B1,B3:B5

Can anyone help me.

like image 940
Ronak Nisar Avatar asked Jul 27 '26 15:07

Ronak Nisar


1 Answers

Like this?

Sub Sample()
    Dim Rng1 As Range, Rng2 As Range
    Dim aCell As Range, FinalRange As Range

    Set Rng1 = Range("A2:E2")
    Set Rng2 = Range("B1:B5")

    Set FinalRange = Rng1

    For Each aCell In Rng2
        If Intersect(aCell, Rng1) Is Nothing Then
            Set FinalRange = Union(FinalRange, aCell)
        End If
    Next

    If Not FinalRange Is Nothing Then Debug.Print FinalRange.Address
End Sub

OUTPUT:

$A$2:$E$2,$B$1,$B$3:$B$5

EXPLANATION: What I am doing here is declaring a temp range as FinalRange and setting it to Range 1. After that I am checking for each cell in Range 2 if it is present in Range 1. If it is then I am ignoring it else adding it using Union to the Range 1

EDIT Question was also cross posted here

like image 154
Siddharth Rout Avatar answered Jul 29 '26 18:07

Siddharth Rout



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!