|
楼主 |
发表于 2022-12-10 12:15
|
显示全部楼层
已找到解决办法,对大批量数据计算不是很快
- Sub 计算地标最近距离()
- Dim i, j, n As Long
- Dim arr, brr, crr, drr
- Dim MinArray, MinArrayIndex As Long
- arr = Sheet1.Range("d2:f" & Cells(Rows.Count, "f").End(xlUp).Row)
- brr = Sheet1.Range("a2:c" & Cells(Rows.Count, "c").End(xlUp).Row)
- ReDim crr(1 To UBound(brr))
- ReDim drr(1 To UBound(arr), 1 To 4)
- For j = 1 To UBound(arr)
- For i = 1 To UBound(brr)
- crr(i) = CalcDistance(arr(j, 3), arr(j, 2), brr(i, 3), brr(i, 2)) '调用公式,计算结果装入数组
- Next
- MinArray = Application.Min(crr) '获取距离最小值
- MinArrayIndex = Application.Match(MinArray, crr, 0) '获取最小值所在的位置(下标)
- For n = 1 To 3
- drr(j, n) = brr(MinArrayIndex, n)
- Next
- drr(j, 4) = MinArray
- Next
- Sheet1.Range("g2").Resize(UBound(arr), 4) = drr
- 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 = xx * xx
- End Function
复制代码 |
|