Option Explicit
Public Const gcLength As Long = 1
Public Const gcStart As Long = 2
Public Const gcEnd As Long = 3
Public Const gcID As Long = 4
Public Const gcPairs As Long = 5
Sub LookForOverlaps()
Dim rRoads As Range, rSort As Range
Dim i1 As Long, i2 As Long
'set up
Set rRoads = ActiveWorkbook.Worksheets("Road Sections").Cells(1, 1).CurrentRegion
Application.ScreenUpdating = False
'sort by start
With ActiveSheet
.Sort.SortFields.Clear
.Sort.SortFields.Add Key:=rRoads.Cells(2, gcStart).Resize(rRoads.Rows.Count - 1, 1), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortTextAsNumbers
.Sort.SetRange rRoads
.Sort.Header = xlYes
.Sort.MatchCase = False
.Sort.Orientation = xlTopToBottom
.Sort.SortMethod = xlPinYin
.Sort.Apply
End With
'do each
With rRoads
For i1 = 2 To .Rows.Count - 1
Application.StatusBar = "Checking " & .Cells(i1, gcStart).Value & " (" & i1 & " out of " & .Rows.Count
For i2 = i1 + 1 To .Rows.Count
If pvtBetween(.Cells(i1, gcStart), .Cells(i2, gcStart), .Cells(i2, gcEnd)) Or _
pvtBetween(.Cells(i1, gcEnd), .Cells(i2, gcStart), .Cells(i2, gcEnd)) Or _
pvtBetween(.Cells(i2, gcStart), .Cells(i1, gcStart), .Cells(i1, gcEnd)) Or _
pvtBetween(.Cells(i2, gcEnd), .Cells(i1, gcStart), .Cells(i1, gcEnd)) Then
If Len(.Cells(i1, gcPairs).Value) = 0 Then
.Cells(i1, gcPairs).Value = .Cells(i1, gcID).Value & "+" & .Cells(i2, gcID).Value
Else
.Cells(i1, gcPairs).Value = .Cells(i1, gcPairs).Value & ", " & _
.Cells(i1, gcID).Value & "+" & .Cells(i2, gcID).Value
End If
End If
Next i2
Next i1
End With
'sort by ID
With ActiveSheet
.Sort.SortFields.Clear
.Sort.SortFields.Add Key:=rRoads.Cells(2, gcID).Resize(rRoads.Rows.Count - 1, 1), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortTextAsNumbers
.Sort.SetRange rRoads
.Sort.Header = xlYes
.Sort.MatchCase = False
.Sort.Orientation = xlTopToBottom
.Sort.SortMethod = xlPinYin
.Sort.Apply
End With
'cleanup
Application.ScreenUpdating = True
Application.StatusBar = False
End Sub
Private Function pvtBetween(X As Long, L As Long, H As Long) As Boolean
pvtBetween = (L <= X) And (X <= H)
End Function
Paul