通过Excel VBA从WCF服务调用方法

时间:2012-06-22 10:59:15

标签: wcf excel-vba vba excel

我已经通过WCF Web服务创建了一个方法。我已将其上传到我的服务器。我想要做的是在Excel VBA宏中调用该方法。有可能吗?

类似的东西:

Dim client As DaybookServicesClient = New DaybookServicesClient()
' Use the 'client' variable to call operations on the service.

' Calls my method
client.ExecuteSQLJob()

' Always close the client.
client.Close()

我如何在Excel VBA中引用我的服务?

2 个答案:

答案 0 :(得分:2)

一种方法可以创建WebGet wcf服务,服务会返回adorecordset xml,在宏上你可以使用以下代码获取记录集

    Public Function GetRSFromString(sXML As String) As Object
   Dim oStream As Object, oRecordset As Object
   Set oStream = CreateObject("ADODB.Stream")
   oStream.Open
   oStream.WriteText sXML
   oStream.Position = 0
   Set oRecordset = CreateObject("ADODB.Recordset")
   oRecordset.Open oStream
   oStream.Close
   Set oStream = Nothing
   Set GetRSFromString = oRecordset
   Set oRecordset = Nothing
End Function


Public Function GetSoapRequest()
    Dim strResult As String
    Dim xmlhtp As Object, xmlDoc As Object, oRecordSetFromXML As Object
    Set xmlhtp = CreateObject("msxml2.xmlhttp.6.0")
    With xmlhtp
            .Open "get", "http://[server]/ServiceName.svc/FunctionName", False
            .setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
            .Send
            Set xmlDoc = CreateObject("msxml2.DOMDocument.6.0")
            strResult = .responseText
            xmlDoc.loadXML strResult
            Set oRecordSetFromXML = AdoFunction .GetRSFromString(xmlDoc.Text)
    End With
    Set xmlDoc = Nothing
    Set xmlhtp = Nothing               
End Function

答案 1 :(得分:0)

您可以使用Web Service Reference Tool从excel调用Web服务,为您的服务生成代理,然后在VBA代码中进行调用。

但是,由于VB和Java(托管服务)之间的互操作性,我试图让它在之前工作并失败。

如果您的呼叫是单向的(VBA代码不需要响应),最好让VBA代码通过msmq向中间服务发送消息,然后中介服务代表您进行呼叫。这是我最终使用的解决方案。