Communicate Between Excel and PHP

February 16th, 2005 | Categories: XML/Services | Tags:
-->

I’m really enjoying the WinHTTP and Web Services (specifically REST) stuff. Even though I need to research quite a bit for each small thing I learn, and I’m just getting started, it’s well worth it.

Last night I figured out how to round trip a variable from VBA to PHP and back. In other words, I learned how to pass a VBA variable to a PHP function (residing in a file on the AutomateExcel server), manipulate the variable, then return the new result back to VBA.

Note: The variable is sent as a string.

rest1For example, the message box in this picture was arrived at by:
1. Sending a variable holding the number 15 over HTTP to a PHP file on AutomateExcel
2. A PHP function takes the variable, Multiplies it by 500, then returns the answer, in this case 7500
3. VBA reads the response and returns the answer in a msgbox

Here’s what the PHP code looks like. Open notepad, copy and paste this info, save the file with the extension php, and upload to your server:

<?php 

$GetNumber=$_GET["PassThis"];
$NewNumber=$GetNumber*500; 

echo $GetNumber. " x 500 = " .$NewNumber; 

?>

I didn’t return the answer in XML to keep the example simple. Here’s the VBA code to send and receive the data, change the connection string to point to the php file you just created:

' Add a reference to Microsoft WinHTTP Services
Const HTTPREQUEST_SETCREDENTIALS_FOR_SERVER = 0

Private Sub GetItems()
Dim MyCon As New WinHttpRequest
Dim sendthis As Double
Dim myanswer As String

    'variable to send
    sendthis = 15

    'Connection string to send
    MyCon.Open "GET", _
    "http://www.automateexcel.com/pl/server500.php" & _
    "?PassThis=" & sendthis

    'send it
    MyCon.Send

    'return it
    myanswer = MyCon.ResponseText
    MsgBox myanswer

End Sub

Note: Add a reference to Microsoft WinHTTP Services

That’s awesome!

Can't get the tutorial to work for you? Need help with your code?
Get answers right away at our AE Excel Support Forums!
  1. February 17th, 2005 at 04:00
    Reply | Quote | #1

    Nice to see your having “fun” Mark, sadly PHP is a bridge to far for me at the mo!!!

  2. Mark
    February 18th, 2005 at 19:45
    Reply | Quote | #2

    I’ve been meaning to start learning it for a year, just testing the waters currently.