How can I send an HTTP POST request to a server from Excel using VBA?
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")URL = "http://www.somedomain.com"objHTTP.Open "POST", URL, FalseobjHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"objHTTP.send ""
If you need it to work on both Mac and Windows, you can use QueryTables:
With ActiveSheet.QueryTables.Add(Connection:="URL;http://carbon.brighterplanet.com/flights.txt", Destination:=Range("A2")) .PostText = "origin_airport=MSN&destination_airport=ORD" .RefreshStyle = xlOverwriteCells .SaveData = True .RefreshEnd With
- Regarding output... I don't know if it's possible to return the results to the same cell that called the VBA function. In the example above, the result is written into A2.
- Regarding input... If you want the results to refresh when you change certain cells, make sure those cells are the argument to your VBA function.
- This won't work on Excel for Mac 2008, which doesn't have VBA. Excel for Mac 2011 got VBA back.
For more details, you can see my full summary about "using web services from Excel."
In addition to the answer of Bill the Lizard:
Most of the backends parse the raw post data. In PHP for example, you will have an array
$_POST in which individual variables within the post data will be stored. In this case you have to use an additional header
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")URL = "http://www.somedomain.com"objHTTP.Open "POST", URL, FalseobjHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded"objHTTP.send "var1=value1&var2=value2&var3=value3"
Otherwise, you have to read the raw post data on the variable