excel 抵销单元格中的函数过帐

jhdbpxl9  于 2023-02-20  发布在  其他
关注(0)|答案(1)|浏览(105)

我创建了一个使用Bing API获取坐标的函数。
我如何抵消上述结果?目标是随时调用该函数,它会将结果发布到所选范围旁边。
例如,您在A1中键入地址,在B1单元格中调用函数CoordinatesBing(A1),然后它在B1和C1中发布搜索结果。

**注意:**这是一个测试,看看我是否可以得到坐标。稍后我将介绍工作流和错误捕获。

Option Explicit
Const bingURL As String = "http://dev.virtualearth.net/REST/v1/Locations?query="
Const apiKey As String = "BingsMapKey"
Private Const ReadyOk As Long = 4

Public Function CoordinatesBing(reqAddress As String) As String
Dim URL As String
Dim reqHTTP As New MSXML2.XMLHTTP60
Dim xmlAddress As String
Dim Latitude As Variant
Dim Longitude As Variant
Dim Result As Range

xmlAddress = WorksheetFunction.EncodeURL(reqAddress)'turns the selected range to Uri encoding

'Makes the request to BingMap
URL = bingURL & xmlAddress & "&o=xml" & "&key=" & apiKey
reqHTTP.Open "GET", URL, False
reqHTTP.send ("")

'Stores the coordinated in these variables.
Latitude = WorksheetFunction.FilterXML(reqHTTP.responseText,"/Response/ResourceSets/ResourceSet/Resources/Location/Point/Latitude")
Longitude = WorksheetFunction.FilterXML(reqHTTP.responseText, "/Response/ResourceSets/ResourceSet/Resources/Location/Point/Longitude")

'This is where I am having difficulties. 
Set Result = ' selects the cell here. I assume
'Post the results
Result.Offset(0, 2).Value = Latitude
Result.Offset(0, 3).Value = Longitude
 
End Function
vxf3dgd4

vxf3dgd41#

你需要把它看作一个只返回一个值的函数,所以你的函数定义应该更像

Public Function CoordinatesBing(ByVal reqAddress As String, ByVal lWhich As Long) As String
    
    'do stuff
    
    If lWhich = 0 Then
        CoordinatesBing = latitude
    Else
        CoordinatesBing = longitude
    End If
    
End Function

对于单元格B1,你可以用0来调用它,对于单元格C1,你可以用1来调用它。这很糟糕,因为http调用是昂贵的,你必须调用这个函数两次才能得到两个坐标。
您可以将公式写成数组公式。这样,您只需调用API一次,但您的用户必须知道如何在两个单元格都选中的情况下输入公式,并使用Ctrl+Shift+Enter。这并不理想。数组公式UDF如下所示

Public Function CoordinatesBing(ByVal reqAddress As String) As String()
        
        Dim sreturn(0 To 1) As String
        
        sreturn(0) = "long"
        sreturn(1) = "lat"
        
        CoordinatesBing = sreturn
  
End Function

Function声明行末尾的那些括号告诉它返回的是一个数组。
如果地址数量有限,第三种选择是使用Sub过程为每个地址生成一个表,然后使用内置的查找函数从表中获取坐标。

相关问题