VBA哈斯汀配方

时间:2016-02-03 10:53:11

标签: excel vba formula haversine

我正在尝试将Haversine公式实现为excel函数。它看起来像这样:

Public Function Haversine(Lat1 As Variant, Lon1 As Variant, Lat2 As Variant, Lon2 As Variant)
Dim R As Integer, dlon As Variant, dlat As Variant, Rad1 As Variant
Dim a As Variant, c As Variant, d As Variant, Rad2 As Variant

R = 6371
dlon = Excel.WorksheetFunction.Radians(Lon2 - Lon1)
dlat = Excel.WorksheetFunction.Radians(Lat2 - Lat1)
Rad1 = Excel.WorksheetFunction.Radians(Lat1)
Rad2 = Excel.WorksheetFunction.Radians(Lat2)
a = Sin(dlat / 2) * Sin(dlat / 2) + Cos(Rad1) * Cos(Rad2) * Sin(dlon / 2) * Sin(dlon / 2)
c = 2 * Excel.WorksheetFunction.Atan2(Sqr(a), Sqr(1 - a))
d = R * c
Haversine = d
End Function

但是当我测试它时,我的距离越来越远...我不明白为什么。对于本主题中使用的坐标:Function to calculate distance between two coordinates shows wrong 我输出20013,44。谁知道这里有什么问题?找不到我的错误......

2 个答案:

答案 0 :(得分:3)

与JavaScript相比,Atan2在Excel中被定义为前置,即Atan2(x,y),而不是Atan2(y,x)。

您需要颠倒两个参数的顺序: -

c = 2 * Excel.WorksheetFunction.Atan2(Sqr(1 - a), Sqr(a))

请参阅this

所以

=haversine(59.3293371,13.4877472,59.3225525,13.4619422)

给出

1.65 km

这是乌鸦飞行时的正确距离。

答案 1 :(得分:0)

很棒的工具!只是强调结果将以公里为单位,因此,如果您想英里将结果乘以0.62137。