Position of a range within another range

XL Pro

Board Regular
Joined
Apr 17, 2002
Messages
249
Office Version
  1. 365
Platform
  1. Windows
What's the easiest what to determine the position of a range within another range via VBA?

In my case, I want to know what column (not the column number) a range falls within another range?

For example:
Range("C1") in Range("C1:G1")
Range("N1") in Range("L1:O1")

I would like to know that C1 is in the first column of C1:G1, N1 would be in the 3rd column of L1:O1.
 
Last edited:

Excel Facts

Do you hate GETPIVOTDATA?
Prevent GETPIVOTDATA. Select inside a PivotTable. In the Analyze tab of the ribbon, open the dropown next to Options and turn it off
Here is a User Defined Function I designed to do that:
Code:
Function ColPos(rng1 As Range, rng2 As Range) As Long
'   rng1 is bigger of two ranges
    
    Dim col1 As Long
    Dim col2 As Long

'   Exit if rng2 not found within rng1
    If Intersect(rng1, rng2) Is Nothing Then Exit Function
    
'   Find the column numbers of each range
    col1 = rng1(1, 1).Column
    col2 = rng2(1, 1).Column
    
'   Return the column number of start of rng2 within rng1
    ColPos = col2 - col1 + 1

End Function
So, then you could use it as a Worksheet formula like this:
Code:
=ColPos(C1:G1,C1)

Or use it in VBA code like this:
Code:
MsgBox ColPos(Range("L1:O1"), Range("P1"))

Note that if the second range is not found within the first, it will return 0.
 
Upvote 0
{facepalm} sometimes the simplest of math can just trip you up!

Thanks Joe4!
 
Upvote 0

Forum statistics

Threads
1,213,510
Messages
6,114,037
Members
448,543
Latest member
MartinLarkin

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top