Vba excel soap запрос

Hoping someone can help with this. I’m trying to test sending a request.xml file using VBA in Excel and can’t quite figure out how to do it. I’d like to have the response be sent to the MessageBox before I can go any further.

When I run the script I can tell that it is connecting to the server, but I’m wondering if authentication is failing because I get a generic response basically saying that it successfully connect to the Apache server, but no response data.

When I use wget and send the request.xml file I get a response.xml file with the data I’m looking for. Any help would be greatly appreciated.

Here’s my test code:

Text

 ' Code Snippets : Some of the source code listed below was taken from the following websites and credit show be given to the respective authors
 '#  http://scn.sap.com/community/epm/blog/2012/08/10/how-to-invoke-a-soap-web-service-from-custom-vba-code
 '#  http://www.vbaexpress.com/forum/showthread.php?t=34354
 '#  http://stackoverflow.com/questions/241725/calling-a-webservice-from-vba-using-soap
 '#  http://brettdotnet.posterous.com/excel-vba-using-a-web-service-with-xmlhttp-we
    'Declare our working variables
    Dim sURL As String
    Dim sEnv As String
       
    'Set and Instantiate our working objects
    Set objHttp = CreateObject("MSXML2.XMLHTTP")
    sURL = "https://www.bluestoreinc.com/bsiwebservice/soaprequest"
      
    
    ' we create our SOAP envelope for submission to the Web Service
     'sEnv = "<?xml version=""1.0"" encoding=""utf-8""?>"
     sEnv = sEnv & "<soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope"">"
     sEnv = sEnv & "  <soap:Header>"
     sEnv = sEnv & "  <soap:Body>"
     sEnv = sEnv & "   <soap:Request>"
     sEnv = sEnv & "    <soap:User>username</soap:User>"
     sEnv = sEnv & "    <soap:Pwd>password</soap:Pwd>"
     sEnv = sEnv & "    <soap:Sku>KT-21-61261-01</soap:Sku>"
     sEnv = sEnv & "   </soap:Request>"
     sEnv = sEnv & "  </soap:Header>"
     sEnv = sEnv & "  </soap:Body>"
     sEnv = sEnv & "</soap:Envelope>"
     
    'we invoke the web service
    'use this code snippet to invoke a web service which requires authentication
     objHttp.Open "GET", sURL, False
     objHttp.setRequestHeader "Content-Type", "text/xml"

    objHttp.send sEnv
    MsgBox objHttp.responseText
    'clean up code
    Set objHttp = Nothing
    Set XMLDOC = Nothing
End Sub

SOAP/XML Request file from vendor:

Text

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope">
   <soapenv:Header/>
   <soapenv:Body>
      <Request>
         <User>USERNAME</User>
         <Pwd>PASSWORD</Pwd>
         <Sku>BT-EP20</Sku>
      </Request>
   </soapenv:Body>
</soapenv:Envelope>

I’m trying to call a web service in an Excel Macro:

Set objHTTP = New MSXML.XMLHTTPRequest
objHTTP.Open "post", "https://www.server.com/EIDEServer/EIDEService.asmx"
objHTTP.setRequestHeader "Content-Type", "text/xml"
objHTTP.setRequestHeader "SOAPAction", "PutSchedule"
objHTTP.send strXML      

And I get back the following response:

  <?xml version="1.0" encoding="utf-8"?>
  <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
      <soap:Fault>
        <faultcode>soap:Client</faultcode>
        <faultstring>Server did not recognize the value of HTTP Header SOAPAction: PutSchedule.</faultstring>
        <detail />
      </soap:Fault>
    </soap:Body>
  </soap:Envelope> 

Anybody out there done something like this before?

shruti1810's user avatar

shruti1810

3,8202 gold badges15 silver badges28 bronze badges

asked Oct 27, 2008 at 23:37

Kevin Colyar's user avatar

You SOAP action should also include namespace of the method
e.g.

"http://tempri.org/PutSchedule"

Find out what the namespace of your Service and add it in front of the method name PutSchedule.

answered Oct 28, 2008 at 1:20

Ray Lu's user avatar

Ray LuRay Lu

26k12 gold badges60 silver badges59 bronze badges

1

Hello, 

I am trying to use VBA to connect to web services. I have to cleanse the code, but the snippet below should give a general idea of what I am trying to do: 

Dim authtoken As String, sEnvBegin As String, sEnvEnd As String, sURL As String

Sub setEnvBeginEnd()
    sURL = "http://api-test.XXXX.net/default.asmx"
    
    sEnvBegin = "<?xml version=""1.0"" encoding=""utf-8""?>" & vbCr
    sEnvBegin = sEnvBegin & "<soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">" & vbCr
    sEnvBegin = sEnvBegin & "<soap:Body>" & vbCr
    
    sEnvEnd = "</soap:Body>" & vbCr
    sEnvEnd = sEnvEnd & "</soap:Envelope>"
    
End Sub

Sub authenticate()

    Dim sEnv As String, sEnvMid As String, appGuid As String, compGuid As String, uName As String, pass As String
    Dim xHTTP As New MSXML2.XMLHTTP, xmlDoc As New DOMDocument
    
    Call setEnvBeginEnd
    
    appGuid = Sheets("Input").Range("B1")
    compGuid = Sheets("Input").Range("B2")
    uName = Sheets("Input").Range("B3")
    pass = Sheets("Input").Range("B4")
    
    sEnvMid = "<Authenticate xmlns=""http://www.XXXX.net/Services"">" & vbCr
    sEnvMid = sEnvMid & "<appId>" & appGuid & "</appId>" & vbCr
    sEnvMid = sEnvMid & "<companyId>" & compGuid & "</companyId>" & vbCr
    sEnvMid = sEnvMid & "<userName>" & uName & "</userName>" & vbCr
    sEnvMid = sEnvMid & "<password>" & pass & "</password>" & vbCr
    sEnvMid = sEnvMid & "</Authenticate>" & vbCr
    
    sEnv = sEnvBegin & sEnvMid & sEnvEnd
    
    With xHTTP
        .Open "Post", sURL, False
        .setRequestHeader "Host", "http://api-test.XXXXX.net"
        .setRequestHeader "Content-Type", "text/xml; charset=utf-8"
        .setRequestHeader "SOAPAction", "http://www.XXXX.net/Services/Authenticate"
        .send (sEnv)
        'xmlDoc.LoadXML .getAllResponseHeaders & vbCr & .Status & .statusText
        'xmlDoc.Save ThisWorkbook.Path & "WebQueryResult.xml"
        Debug.Print sEnv
        Debug.Print .getAllResponseHeaders
        Debug.Print .responseText
        Debug.Print .Status
        Debug.Print .statusText
    End With
    
    
End Sub

Now, when I run this code I get a HTTP error 400 (Bad Request). When I monkey around with the SOAPAction header, I sometimes get a 500 error and an XML response saying the ‘SOAPAction’ request is not recognized. 

Using Fiddler, I get the following header data:

POST http://api-test.XXXX.net/default.asmx HTTP/1.1
Accept: */*
Accept-Language: en-us
soapaction: http://www.XXXX.net/Services/Authenticate
Content-Type: text/xml; charset=utf-8
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)
Host: api-test.XXXX.net
Content-Length: 519
Connection: Keep-Alive
Pragma: no-cache

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<Authenticate xmlns="http://www.XXXX.net/Services">
<appId>12345678-0910-1112-1314-151617181920</appId>
<companyID>21222324-2526-2728-2930-313233343536</companyId>
<userName>Badasstronaut@troubleshot.com</userName>
<password>God</password>
</Authenticate>
</soap:Body>
</soap:Envelope>

So why on earth is the ‘SOAPAction’ header coming in lower-case? Also, the XML matches a request that works, but this one will only return errors. 

Any help on this would be greatly appreciated! 

Содержание

  1. SOAP Request via VBA in Excel
  2. Popular Topics in Microsoft Office
  3. 8 Replies
  4. Read these next.
  5. Not sure what to think. career moves.
  6. Bypassing School Wi-Fi and Using Cell Phone Hot Spot
  7. Snap! — Pluto, See-Through Wood, Fighting Scam Texting, PLATO, Counterportation
  8. End user training
  9. OneDrive Data Encryption
  10. How to invoke a SOAP Web Service from custom VBA Code
  11. Access SOAP Web Services from Excel
  12. SOAP through VBA
  13. 1 Answer 1

SOAP Request via VBA in Excel

Hoping someone can help with this. I’m trying to test sending a request.xml file using VBA in Excel and can’t quite figure out how to do it. I’d like to have the response be sent to the MessageBox before I can go any further.

When I run the script I can tell that it is connecting to the server, but I’m wondering if authentication is failing because I get a generic response basically saying that it successfully connect to the Apache server, but no response data.

When I use wget and send the request.xml file I get a response.xml file with the data I’m looking for. Any help would be greatly appreciated.

Here’s my test code:

SOAP/XML Request file from vendor:

Popular Topics in Microsoft Office

It might be easier to use PowerShell to call the web service, and create a CSV file you can then read into Excel?

Thanks, I’ll have to try that. In the meantime, I did get further along with my initial code. In my first post I didn’t realize until later that the SOAP Request has to be in the exact format received by vendor for authentication to work. Also, changing «GET» to «PUT» helped as well. I’m a novice to both SOAP/XML and VBA so this has been quite the challenge.

Now I’m able to get the response.xml data, but I’m not sure how to map certain fields to the proper cells in Excel.

Here’s the code that worked:

I finally got the results I was looking for. Here’s what I needed to do: Enter vendor part# in cell B3 and get data from SOAP Request/Response and only display ItemCost, Quantity on Hand, and Warehouse Location in cells, B6,C6 and D6.

Dim Resp As New MSXML2.DOMDocument60 in this line it is giving error for me «User defined type not defined» %uFEFF

Also please guide me how I will load the desired «wsdl» file for the individual request

Can you tell me what «//Response/ItemCost» means?

I have a similar SOAP Message, but the field which I return is called

What necessary changes should I make?

how can I extract the value of the node «User» with the excel function «FILTER.XML»%uFEFF or via VBA?

What is the path to use?

This topic has been locked by an administrator and is no longer open for commenting.

To continue this discussion, please ask a new question.

Read these next.

Not sure what to think. career moves.

I left an IT manager/admin position about 4 months ago to try my hand at technology design with an architectural firm. I left thinking I would enjoy the design and specification more than systems and user support. Turns out the position is more helpdesk t.

Bypassing School Wi-Fi and Using Cell Phone Hot Spot

Over the past month, we have started to have trouble with students connecting school devices to their cell phone hot spots, and using this to bypass the rules that are in place. What creative ideas do you have t.

Snap! — Pluto, See-Through Wood, Fighting Scam Texting, PLATO, Counterportation

Your daily dose of tech news, in brief. Welcome to the Snap! Flashback: March 17, 1948: William Gibson, inventor of the term cyberspace, was born (Read more HERE.) Bonus Flashback: March 17, 1958: Vanguard 1, oldest man-made object in Ear.

End user training

Anyone have suggestions on end user email security training, like Knowbe4 and InfosecIQ?

OneDrive Data Encryption

Does anyone use any tools for encrypting sensitive data that gets stored in onedrive?I have a tech privacy savvy CEO who has used boxcryptor for years to add an extra layer of protection for sensitive files he stores in onedrive, but Dropbox has purchas.

Источник

How to invoke a SOAP Web Service from custom VBA Code

Recently I have been involved with several integration projects between different EPM products. Initially it was quite challenging because as with any integration project the devil is always in the detail. The great thing with SAP EPM products is that there are web services for major processes and functions that need to be performed.

I needed to invoke a web service for an EPM product but had to do it in SAP BPC NW. Now there is several methods to invoke a web service from BPC NW, but it wouldnt be transportable to the MS product. So the solution was to invoke it from the client machine using VBA because on the client machine it can invoke any web service. Because SAP BPC uses Microsoft Office, you can create custom macros and VBA code to execute specific functions and functionality.

The answer to my particular challenge was to invoke a Web Service using custom VBA code embedded in an BPC Input Schedule and Report. Now there are several tutorials and links out on the internet which give you sample code to invoke a Web Service using VBA, but one of the major reasons for writing this blog is is to show how this approach can be used to solve several challenges and how powerful it can be.

Imagine some of the following scenarios:

  • Invoking a FIM job from a click of a button on a report or input schedule.
  • Invoking a BPC web service to perform a specific action
  • Export data of BPC into another EPM application but simply invoking a web service to create a KPI in SSM

If you are able to get the WSDL of the Web Service, you can build your SOAP message and invoke the web service to perform the desired function. This VBA code is used to call a SOAP Web Service. It is possible to invoke a REST Web Service which BPC 10 uses, I will do this in another blog detailing a scenario in which this code could be used to solve certain business requirements.

VBA Code example : This is a simply Sub Routine in which will invoke a web service using the MSXML2 Object. This object is part of the Microsoft XML 6.0 library which is a pre-requisite for the EPM Add-In and should be installed on all client machines.

Normally I am not a big fan of using custom VB code in BPC Input Schedules and Reports because of the complexity it can introduce and that in allot of occasions you can expect unexpected behavior on different clients. For example: It works on a Windows 7 machine, but doesn’t work on Windows XP, etc. So a word of caution when using this approach is to understand the risks associated with running code on the client and its implications regarding security.

Hopefully this helps people out there solve certain challenges

Источник

Access SOAP Web Services from Excel

If your spreadsheet needs to access constantly updated data, or if you need to access services hosted on another computer, Excel’s Web Services support will enable you to get connected.

SOAP-based Web Services have been a key part of Microsoft’s plans for .NET, as well as a common feature of toolkits from other vendors. SOAP (the acronym doesn’t mean anything) is a protocol that uses XML to transmit information between systems. In the case you’ll explore here, it’s used to call procedures and return values. A companion specification, Web Service Definition Language (WSDL), describes Web Services so that applications can connect to them easily. Microsoft’s Web Services Reference Tool can take a WSDL file and generate VBA code your application can use to access SOAP-based web services.

This tutorial uses Excel features that are available only in Excel XP and Excel 2003 on Windows. Earlier versions of Excel do not support this, and neither do current or announced Macintosh versions of Excel.

Making this work requires downloading the Office Web Services Toolkit. As its location has changed a few times, it’s easiest to go to http://www.microsoft.com/downloads/search.aspx and search for «Office Web Services Toolkit». Separate versions are available for Office XP and Office 2003. You’ll need to install this toolkit, using the directions that come with it, before proceeding with this tutorial.

Once you’ve installed the toolkit, you can start connecting your spreadsheet to web services. To get to the Web Service References Tool (its name inside of Excel), you’ll need to select Tools » Macro » Visual Basic Editor. On the Tools menu of the VBE, you’ll find Web Services References. Selecting this brings up the dialog box shown in figure.

The Microsoft Office Web Services Toolkit in action

You can use the search features in the top left of this dialog to find services through Microsoft’s Universal Discovery, Description and Integration (UDDI) service, or you can enter a URL for the WSDL file at the lower left. You can find a listing of public services at http://xmethods.net/ , though you should definitely test to make sure the services still work before you integrate them with your spreadsheets. Many services also require license keys and sometimes license payments, but for this example you’ll use one that is available for free. It returns the IP address for a given domain name.

Start by telling Excel which service you want to use-in this case, http://www.cosme.nu/services/dns.php?wsdl . Enter that value in the URL: box at the bottom left and click Search. A search result of dns will appear in the top right, as shown in figure. Check the box to its left.

Telling the Web Services Toolkit to generate code for a web service

Clicking the Add button will make Excel generate VBA code for the service, as shown in figure.

VBA code generated by the Web Services Toolkit for accessing the dns service

Next, close the VBE and set up a very simple spreadsheet such as the one shown in figure.

A spreadsheet for adding web services

To add a button for calling the service, display the Control toolbar by right-clicking a toolbar and choosing Control Toolbox from the pop-up menu. Click the button icon, and then click the spreadsheet wherever you want the button to go. Right-click the button, and choose Properties from the pop-up menu. Under Name, enter GetData ; under Caption, enter Get IP Address . Close the Properties dialog box, and your spreadsheet should look something like that shown in figure.

Spreadsheet with button for calling web services

To add the final piece, right-click the button you added and choose View Code. In the window that appears, enter this subroutine:

This code is pretty simple. It references the object the toolkit created for the web service, and creates variables for the name and IP address. It collects the name from cell B2, calls the web service with the name as an argument, and then puts the value returned into cell B3. Once you’ve entered this code and closed the VBE, you can leave design mode by making sure the triangle and ruler icon at the left of the Control toolbar isn’t highlighted. The spreadsheet will now enable you to enter a domain name in cell B2. Clicking the Get IP Address button will put the IP address corresponding to that domain name in cell B3. Figures show this spreadsheet in action with different domain names.

A retrieved IP address

IP address resolution is one of the simpler services out there, but many times services this simple can be very useful in a spreadsheet — for instance, for currency converters, price retrieval, postal code processing, and much more. You don’t even need to learn about SOAP or WSDL to use these services, as the Web Services Toolkit takes care of all of that for you.

A few caveats are worth mentioning, however. First, the computer has to be connected to a network for a web service to work. You probably don’t want to create spreadsheets that depend heavily on web services if their users will be working on them at 30,000 feet and will be thoroughly disconnected. (Spreadsheets such as this one, which uses a web service to populate fields but doesn’t need to be connected constantly, are probably OK.)

The other major issue with web services generally is that the field is in significant flux. At the time of this writing, SOAP had moved from Version 1.1 to 1.2, and a new version of WSDL was under development; what’s more, many people feel UDDI might eventually be replaced with other technologies. For now, be certain to test the services you use, and keep an eye out for new versions of the Office Web Services Toolkit.

Источник

SOAP through VBA

I am attempting to pull the info that the following site pulls: http://gis.calhouncounty.org/ParcelViewer/index.html. If you type in PPIN 66078 and then click Property Taxes, it will bring up data. I am attempting to recreate this SOAP request in VBA, but unsuccessfully. It calls the service, but all data in the response is blank. I got so frustrated that I even recreated the full header set, to no avail. Maybe there is a cookie issue, but the cookies on my computer don’t seem to expire quickly. Here’s what I have in the extract:

Any help is incredibly appreciated! -Andy

1 Answer 1

You are not error checking. Adapt the following error checking to your code. err.number, err.description, err.source, file.status, file.statustext, file.getallresponseheaders .

The URL has to be 100% correct. Unlike a browser there is no code to fix urls.

The purpose of my program is to get error details.

How I get a correct URL is to type my url in a browser, navigate, and the correct URL is often in the address bar. The other way is to use Properties of a link etc to get the URL.

Also Microsoft.XMLHTTP maps to Microsoft.XMLHTTP.1.0. HKEY_CLASSES_ROOTMsxml2.XMLHTTP maps to Msxml2.XMLHTTP.3.0. Try a later one

Try this way using xmlhttp. Edit the url’s etc. If it seems to work comment out the if / end if to dump info even if seeming to work. It’s vbscript but vbscript works in vb6.

Also see if these other objects work.

Also be aware there is a limit on how many times you can call any particular XMLHTTP object before a lockout occurs. If that happens, and it does when debugging code, just change to a different xmlhttp object

I get this running your code.

Then I msgbox out responsebody and I have data sending cat rather than what’s in your spreadsheet.

Источник

To access a SOAP web service (such as a Syspro web service) from Visual Basic for Applications (such as an Excel 2003 macro), you can download Microsoft’s SOAP toolkit and access that from Visual Basic.

If you tailor the example code from Microsoft’s SOAP toolkit to make it easy to call Syspro functions; here’s a code snippet example:

Dim GUID as String
Dim XmlOut as String
Dim WebServicesBaseURL = "http://example.com/sysprowebservices"

GUID = LogonToSysproViaWebServices()
XmlOut = CreateSalesOrderWebServices(GUID, "SORTOI", XmlParameters, XmlIn)

Private Function LogonToSysproViaWebServices() As String

    Dim XmlIn As String
    Dim XmlOut As String
    Dim GUID As String

    XmlIn = ""

    Dim objSysproWS As New Syspro_Utilities_Web_Service
    objSysproWS.Setup WebServicesBaseURL

    XmlOut = objSysproWS.Logon(Operator, OperatorPassword, CompanyId, CompanyPassword, LanguageCode, LogLevel, EncoreInstance, XmlIn)

    GUID = Trim(XmlOut)

    Set objSysproWS = Nothing

    LogonToSysproViaWebServices = GUID

End Function

Private Function CreateSalesOrderWebServices(ByRef GUID As String, ByRef BusinessObject As String, ByRef XmlParameters As String, ByRef XmlIn As String) As String
    Dim XmlOut As String
    Dim objSysproWS As New Syspro_Transaction_Web_Service
    objSysproWS.Setup WebServicesBaseURL

    XmlOut = objSysproWS.Post(GUID, BusinessObject, XmlParameters, XmlIn)

    Set objSysproWS = Nothing

    CreateSalesOrderWebServices = XmlOut

End Function ' CreateSalesOrderWebServices

Place the following code in a Class Module in Excel; call the moduleSyspro_Utilities_Web_Service, or change the above code to match whatever you call it.

'*****************************************************************
' This is based on Microsoft-generated code from:
' http://msdn.microsoft.com/en-us/magazine/cc163837.aspx
' ... but it has been modified to make the URL configurable.
'
'*****************************************************************
'This class was created by the Microsoft Office 2003 Web Services Toolkit.
'
'Description:
'This class is a Visual Basic for Applications class representation of the 'Web service as defined by http://localhost/sysprowebservice/transaction.asmx?wsdl.
'
'To Use:
'Dimension a variable as new clsws_Service, and then write code to
'use the methods provided by the class.
'Example:
' Dim ExampleVar as New clsws_Service
' debug.print ExampleVar.wsm_Post("Sample Input")
'
'For more information, see Complex Types in Microsoft Office 2003
'Web Services Toolkit Help.
'
'Changes to the code in this class may result in incorrect behavior.
'
'*****************************************************************

Option Explicit

'Dimensioning private class variables.
Private sc_Service As SoapClient30

' e.g. Private Const c_WSDL_URL As String = "http://localhost/sysprowebservices/utilities.asmx?WSDL"
' e.g. Private Const c_WSDL_URL As String = "http://www.example.com/sysprowebservices2/utilities.asmx?WSDL"
' The last part of the line MUST be "/utilities.asmx?WSDL".
'Private Const c_WSDL_URL As String = "http://localhost/sysprowebservices/utilities.asmx?WSDL"

Private c_WSDL_URL As String
Private Const c_WSDL_URL_Extension As String = "/utilities.asmx?WSDL"

Private Const c_SERVICE As String = "Service"
Private Const c_PORT As String = "ServiceSoap"
Private Const c_SERVICE_NAMESPACE As String = "http://www.syspro.com/ns/utilities/"


Private Sub Class_Initialize()

End Sub


Public Sub Setup(ByVal c_WSDL_URL_Base As String)
    '*****************************************************************
    'This subroutine will be called each time the class is instantiated.
    'Creates sc_ComplexTypes as new SoapClient30, and then
    'initializes sc_ComplexTypes.mssoapinit2 with WSDL file found in
    'http://localhost/sysprowebservices/transaction.asmx?wsdl.
    '*****************************************************************
    
    Dim str_WSML As String
    ' WSML: Default value is "".
    ' This string is in Web Services Meta Language (WSML).
    ' This is a required parameter only when using custom type mappers.
    str_WSML = ""
    Set sc_Service = New SoapClient30
    ' Set sc_Service = Server.CreateObject("MSSOAP.SoapClient30")
    
    ' Not needed:
    'sc_Service.ClientProperty("ServerHTTPRequest") = True

    c_WSDL_URL = c_WSDL_URL_Base & c_WSDL_URL_Extension

    sc_Service.MSSoapInit (c_WSDL_URL)
    
    ' Doesn't work; reason unknown:
    'sc_Service.MSSoapInit2 c_WSDL_URL, str_WSML, c_SERVICE, c_PORT, c_SERVICE_NAMESPACE
    
    'Use the proxy server defined in Internet Explorer's LAN settings by
    'setting ProxyServer to 
    sc_Service.ConnectorProperty("ProxyServer") = ""

    'Autodetect proxy settings if Internet Explorer is set to autodetect
    'by setting EnableAutoProxy to True
    sc_Service.ConnectorProperty("EnableAutoProxy") = True

End Sub


Private Sub Class_Terminate()
    '*****************************************************************
    'This subroutine will be called each time the class is destructed.
    'Sets sc_ComplexTypes to Nothing.
    '*****************************************************************
    'Error Trap
    On Error GoTo Class_TerminateTrap
    Set sc_Service = Nothing
    Exit Sub

Class_TerminateTrap:
    ServiceErrorHandler ("Class_Terminate")

End Sub


Private Sub ServiceErrorHandler(str_Function As String)
    '*****************************************************************
    'This subroutine is the class error handler. It can be called from any
    'class subroutine or function when that subroutine or function
    'encounters an error. Then, it will raise the error along with the
    'name of the calling subroutine or function.
    '*****************************************************************

    'SOAP Error
    If sc_Service.FaultCode  "" Then
        Err.Raise vbObjectError, str_Function, sc_Service.FaultString

    'Non SOAP Error
    Else
        Err.Raise Err.Number, str_Function, Err.Description
    End If
End Sub


Public Function Logon(ByVal Operator As String, ByVal OperatorPassword As String, ByVal CompanyId As String, ByVal CompanyPassword As String, ByVal LanguageCode As String, ByVal LogLevel As String, ByVal EncoreInstance As String, ByVal XmlIn As String) As String

    '*****************************************************************
    'Proxy function created from
    'http://localhost/sysprowebservice/utilities.asmx?wsdl.
    '
    '"Logon" is defined as XML. See Complex Types: XML Variables
    'in Microsoft Office 2003 Web Services Toolkit Help for details on
    'implementing XML variables.
    '*****************************************************************
    'Error Trap
    On Error GoTo Logon_ErrorHandler
    Logon = sc_Service.Logon(Operator, OperatorPassword, CompanyId, CompanyPassword, LanguageCode, LogLevel, EncoreInstance, XmlIn)
    Exit Function

Logon_ErrorHandler:
    ServiceErrorHandler "Logon"

End Function


Public Function Logoff(ByVal Operator As String) As String

    '*****************************************************************
    'Proxy function created from
    'http://localhost/sysprowebservice/utilities.asmx?wsdl.
    '
    '"Logoff" is defined as XML. See Complex Types: XML Variables
    'in Microsoft Office 2003 Web Services Toolkit Help for details on
    'implementing XML variables.
    '*****************************************************************
    'Error Trap
    On Error GoTo Logoff_ErrorHandler
    Logoff = sc_Service.Logoff(Operator)
    Exit Function

Logoff_ErrorHandler:
    ServiceErrorHandler "Logoff"

End Function

' TODO: Create other routines: GetLogonProfile, Run.

Place the following code in a Class Module in Excel; call the moduleSyspro_Transaction_Web_Service, or change the above code to match whatever you call it.

'*****************************************************************
' Proxy to post to the a web service.
'
' This is based on Microsoft-generated code from:
' http://msdn.microsoft.com/en-us/magazine/cc163837.aspx
' ... but it has been modified to make the URL configurable.
'
'*****************************************************************
'This class was created by the Microsoft Office 2003 Web Services Toolkit.
'
'Description:
'This class is a Visual Basic for Applications class representation of the 'Web service as defined by http://localhost/sysprowebservice/transaction.asmx?wsdl.
'
'To Use:
'Dimension a variable as new clsws_Service, and then write code to
'use the methods provided by the class.
'Example:
' Dim ExampleVar as New clsws_Service
' debug.print ExampleVar.wsm_Post("Sample Input")
'
'For more information, see Complex Types in Microsoft Office 2003
'Web Services Toolkit Help.
'
'Changes to the code in this class may result in incorrect behavior.
'
'*****************************************************************

Option Explicit

'Dimensioning private class variables.
Private sc_Service As SoapClient30

Dim c_WSDL_URL As String
Private Const c_WSDL_URL_Extension As String = "/transaction.asmx?WSDL"

Private Const c_SERVICE As String = "Service"
Private Const c_PORT As String = "ServiceSoap"
Private Const c_SERVICE_NAMESPACE As String = "http://www.syspro.com/ns/transaction/"


Private Sub Class_Initialize()

End Sub


Public Sub Setup(ByVal c_WSDL_URL_Base As String)
    '*****************************************************************
    'This subroutine will be called each time the class is instantiated.
    'Creates sc_ComplexTypes as new SoapClient30, and then
    'initializes sc_ComplexTypes.mssoapinit2 with WSDL file found in
    'http://localhost/sysprowebservices/transaction.asmx?wsdl.
    '*****************************************************************

    Dim str_WSML As String
    str_WSML = ""
    Set sc_Service = New SoapClient30
    ' Set sc_Service = Server.CreateObject("MSSOAP.SoapClient30")
    
    ' Not needed:
    'sc_Service.ClientProperty("ServerHTTPRequest") = True

 c_WSDL_URL = c_WSDL_URL_Base & c_WSDL_URL_Extension

    sc_Service.MSSoapInit (c_WSDL_URL)
    
    ' Doesn't work; reason unknown:
    'sc_Service.MSSoapInit2 c_WSDL_URL, str_WSML, c_SERVICE, c_PORT, c_SERVICE_NAMESPACE

    'Use the proxy server defined in Internet Explorer's LAN settings by
    'setting ProxyServer to 
    sc_Service.ConnectorProperty("ProxyServer") = ""

    'Autodetect proxy settings if Internet Explorer is set to autodetect
    'by setting EnableAutoProxy to True
    sc_Service.ConnectorProperty("EnableAutoProxy") = True

End Sub


Private Sub Class_Terminate()
    '*****************************************************************
    'This subroutine will be called each time the class is destructed.
    'Sets sc_ComplexTypes to Nothing.
    '*****************************************************************
    'Error Trap
    On Error GoTo Class_TerminateTrap
    Set sc_Service = Nothing
    Exit Sub

Class_TerminateTrap:
    ServiceErrorHandler ("Class_Terminate")

End Sub


Private Sub ServiceErrorHandler(str_Function As String)
    '*****************************************************************
    'This subroutine is the class error handler. It can be called from any
    'class subroutine or function when that subroutine or function
    'encounters an error. Then, it will raise the error along with the
    'name of the calling subroutine or function.
    '*****************************************************************

    'SOAP Error
    If sc_Service.FaultCode  "" Then
        Err.Raise vbObjectError, str_Function, sc_Service.FaultString

    'Non SOAP Error
    Else
        Err.Raise Err.Number, str_Function, Err.Description
    End If
End Sub


Public Function Post(ByVal UserId As String, ByVal BusinessObject As String, ByVal XmlParameters As String, ByVal XmlIn As String) As String

    '*****************************************************************
    'Proxy function created from
    'http://localhost/sysprowebservice/transaction.asmx?wsdl.
    '
    '"Post" is defined as XML. See Complex Types: XML Variables
    'in Microsoft Office 2003 Web Services Toolkit Help for details on
    'implementing XML variables.
    '*****************************************************************
    'Error Trap
    On Error GoTo Post_ErrorHandler
    Post = sc_Service.Post(UserId, BusinessObject, XmlParameters, XmlIn)
    Exit Function

Post_ErrorHandler:
    ServiceErrorHandler "Post"

End Function

In Excel, in the Microsoft Visual Basic for Applications window, you will need to go to Tools / References and add these references, if you not using late binding to the Microsoft SOAP library:

  • Microsoft Soap Type Library v3.0
  • Microsoft Soap WinHttp Connector Type Library (v3.0)
  • Microsoft Soap WinInet Connector Type Library (v3.0)

Microsoft’s SOAP libraries have been deprecated

Microsoft recommends you use VSTO (VIsual Studio Tools for Office) going forward.

The SOAP toolkit doesn’t work on Windows 2008 R2 Server

Microsoft’s SOAP libraries have been deprecated, but if you have applications that still want to use SOAP, there are still ways to do that.

Firstly, I found that the Microsoft SOAP libraries still work on Windows XP, Windows 7 (both 32 and 64-bit), but NOT on Windows Server 2008 R2.

They don’t seem to work on Windows Server 2008 R2 because the system can’t find the SOAP DLL’s in the registry, because the system seems to use new, different, or wrong registry keys to locate the SOAP DLL’s:

On Windows Server 2008 R2, the system looked, unsuccessfully, for this registry key:

HKCRWow6432NodeCLSID{the-GUID}InprocHandler

but on Windows 7 64-bit, where it was successful, it looks for this registry key:

HKCRWow6432NodeCLSID{the-GUID}InprocServer32.

(This was discovered using Process Monitor to watch registry activity.

How to access SOAP web services from Windows Server 2008 R2

One solution to accessing SOAP is to create a .Net SOAP client (create a project, add a web service to your SOAP endpoint; add a subroutine to call that SOAP endpoint). Then expose that as a COM object so that you can consume your newly created DLL in VBA or where-ever you want.

NOTE for developers

Visual Studio 2010 must be run As Administrator so that you can test the DLL when you run it from Visual Studio as the SoapClient is exposed as a COM Object and needs to be registered when it is built so that it can be found when it is run.

(You can also manually register it using regasm; again you must run as Administrator.)

On the client’s machine, it doesn’t matter where you put the DLL on the client’s machine but the DLL must be registered using regasm.

See Also

  • The Code Snippet in Syspro’s VBScript editor – there’s a code snippet there for calling SOAP.

Понравилась статья? Поделить с друзьями:
  • Vba excel refresh all connections
  • Vba excel show all sheets
  • Vba excel redim что такое
  • Vba excel sheets names
  • Vba excel redim preserve subscript out of range