I have this script that runs ok as lat long are not the same. When they are the same I get run time error 11 can't divide by zero. Is there a way to trap this error. Any help is appreciated.
Private Function ACos(X As Double) As Double
ACos = Atn(-X / Sqr(-X * X + 1)) + 2 * Atn(1)
End Function
Sub CalculateDistance()
Application.ScreenUpdating = False
Set ws1 = Sheets("Input_Data")
Set ws2 = Sheets("Output")
Set ws3 = Sheets("Process_Data")
Set ws4 = Sheets("Start")
Set ws5 = Sheets("dyn RN")
Dim D As Single
Dim L1 As Single
Dim L2 As Single
Dim G1 As Single
Dim G2 As Single
Dim Name1, Nam2 As String
Dim k, i, Dist As Long
Const pi = 3.1415926
i = Range("A1").End(xlDown).Row
For k = i To 2 Step -1
Lat1 = Format(ThisWorkbook.Worksheets("Process_Data").Cells(k, 3))
Long1 = Format(ThisWorkbook.Worksheets("Process_Data").Cells(k, 4))
Lat2 = Format(ThisWorkbook.Worksheets("Process_Data").Cells(k, 5))
Long2 = Format(ThisWorkbook.Worksheets("Process_Data").Cells(k, 6))
'-------------------Match Source and Target----------------------------
'If source and Target are equal then their distance is zero.
Name1 = ws3.Cells(k, 1)
Name2 = ws3.Cells(k, 2)
If Left(Name1, 7) = Left(Name2, 7) Then
ws3.Cells(k, 7) = 0
GoTo line1
Else
L1 = (90 - Lat1) * (pi / 180)
L2 = (90 - Lat2) * (pi / 180)
G1 = Long1 * (pi / 180)
G2 = Long2 * (pi / 180)
End If
D = ACos((Cos(L1) * Cos(L2) + Sin(L1) * Sin(L2) * Cos(G1 - G2)))
Dist = D * 3963
ThisWorkbook.Worksheets("Process_Data").Cells(k, 7) = Format(Dist)
line1:
Next k
End Sub
Bookmarks