carlAlex
1/25/2017 - 10:23 AM

## Polygon and points

Polygon and points

``````https://www.mrexcel.com/forum/excel-questions/713005-does-point-fall-within-polygon-visual-basic-applications-function.html

Function PointInPolygon(rXY As Range, rpolyXY As Range) As Boolean
' Function checks if X,Y given in rXY falls within complex _
polygon as defined by node list rpolyXY. _
rXY to be 2 cell range with one X and one Y value _
rpolyXY to be 2 column range with for each node on the polygon _
the X and the Y point

Dim i As Integer, j As Integer, polySides As Integer
Dim oddNodes As Boolean
Dim x As Double, y As Double
Dim aXY As Variant

oddNodes = False
x = rXY.Cells.Value2(1, 1)
y = rXY.Cells.Value2(1, 2)
aXY = rpolyXY.Value

polySides = rpolyXY.Rows.Count
j = polySides - 1

For i = 1 To polySides
If (((aXY(i, 2) < y And aXY(j, 2) >= y) _
Or (aXY(j, 2) < y And aXY(i, 2) >= y)) _
And (aXY(i, 1) <= x Or aXY(j, 1) <= x)) Then
oddNodes = oddNodes Xor (aXY(i, 1) + (y - aXY(i, 2)) / (aXY(j, 2) - aXY(i, 2)) * (aXY(j, 1) - aXY(i, 1)) < x)
End If
j = i
Next i
PointInPolygon = oddNodes
End Function``````