提问人:Bobdiddlydo 提问时间:4/4/2023 最后编辑:karelBobdiddlydo 更新时间:11/6/2023 访问量:83
如何在同一行中添加多个VBA WorksheetFunctions?
How do I add multiple VBA WorksheetFunctions in the same line?
问:
我有很长的公式来计算哪个发射点离目的地最近。
运行时错误 438
对象不支持此属性或方法。
Sub GetClosestLocation(dest_lat, dest_long)
Dim sp As Variant
Dim expr, a, b, c, launch_name, launch_lat, launch_long As Range
'Get Names on Launch Points sheet
a = Sheets("Launch Points").Range("F" & Rows.Count).End(xlUp).Row
expr = "F10" + Trim(Str(a))
Set launch_name = Sheets("Launch Points").Range(expr)
'Get Lattitudes on Launch Points sheet
b = Sheets("Launch Points").Range("B" & Rows.Count).End(xlUp).Row
expr = "B10" + Trim(Str(b))
Set launch_lat = Sheets("Launch Points").Range(expr)
'Get Longitudes on Launch Points sheet
c = Sheets("Launch Points").Range("C" & Rows.Count).End(xlUp).Row
expr = "C10" + Trim(Str(c))
Set launch_long = Sheets("Launch Points").Range(expr)
With Application
sp = .Lookup(1, 1 / .Frequency(0, .Sin((.Radians(launch_lat - dest_lat)) / 2) ^ 2 + .Sin((.Radians(launch_long - dest_long)) / 2) ^ 2 * .Cos(.Radians(launch_lat)) * .Cos(.Radians(dest_lat))), launch_name)
End With
Range("F17") = sp
End Sub
该公式在 VBA 之外工作。
我可能使用了完全错误的方法。对我有用的是这个公式。我正在尝试将其放入VBA中,然后获取信息 (发射点名称、地址、城市和省份):
=LOOKUP(1, 1 / FREQUENCY(0, SIN((RADIANS('Launch Points'!B10:B119 - B14)) / 2) ^ 2 + SIN((RADIANS('Launch Points'!C10:C119 - C14)) / 2) ^ 2 * COS(RADIANS('Launch Points'!B10:B119)) * COS(RADIANS(B14))), 'Launch Points'!F10:F119)
答:
1赞
Tim Williams
4/4/2023
#1
未经测试,因为我没有任何测试数据,但这样的东西应该可以工作:
Function GetClosestLocation(dest_lat, dest_long)
Dim f As String, lr As Long, ws As Worksheet
f = "=LOOKUP(1, 1 / FREQUENCY(0, SIN((RADIANS(B10:B119 - <dlat>)) / 2) ^ 2 + " & _
"SIN((RADIANS(C10:C<lr> - <dlong>)) / 2) ^ 2 * COS(RADIANS(B10:B<lr>)) * " & _
"COS(RADIANS(<dlat>))), F10:F<lr>)"
Set ws = ThisWorkbook.Worksheets("Launch Points")
lr = ws.Range("F" & Rows.Count).End(xlUp).Row
f = Replace(f, "<lr>", lr)
f = Replace(f, "<dlat>", dest_lat)
f = Replace(f, "<dlong>", dest_long)
GetClosestLocation = ws.Evaluate(f)
End Function
评论
0赞
Bobdiddlydo
4/4/2023
这似乎已经成功了。谢谢伙计!
评论
.
Sin
Cos
WorksheetFunction
VBA.Math
expr = "F10:F" + Trim(Str(a))
其他范围也是如此。此外 - 您应该只需要获取最后一行一次 - 假设 F、B 和 C 列的数字应该相同。launch_lat - dest_lat
- 你不能这样减去两个数组。+
&