VBA学习笔记(二):由经纬度计算距离VBA代码
一、由经纬度计算距离VBA代码:
Sub Example02() Dim Distance As Double Dim lat1 As Double Dim lon1 As Double Dim lat2 As Double Dim lon2 As Double '位置1:尧都区华洲路面粉厂 lat1 = 36.07812 lon1 = 111.54295 '位置2:尧都区秦署路党校 lat2 = 36.07436 lon2 = 111.494613 Distance = CalcDistance(lat1, lon1, lat2, lon2) End Sub Function CalcDistance(ByVal lat1 As Double, ByVal lon1 As Double, ByVal lat2 As Double, ByVal lon2 As Double) As Double '经纬度计算距离公式,得出结果单位为米 CalcDistance = 6378137 * 2 * Application _ .Asin(Sqr(SumSq(Sin((Radians(lat1) - Radians(lat2)) / 2)) + Cos(Radians(lat1)) * _ Cos(Radians(lat2)) * SumSq(Sin((Radians(lon1) - Radians(lon2)) / 2)))) End Function Function Radians(latORlon As Double) As Double '度转换成弧度公式为X*π/180 PI14 = 3.14159265358979 Radians = latORlon * PI14 / 180 End Function Function SumSq(xx As Double) As Double '根据实际情况,简化了SumSq函数的代码编写 SumSq = xx * xx End Function