在Excel VBAmacros中处理REST API处理

下面的VBA代码应该调用REST API来授予用户对文件的访问权限。 如果REST API返回允许,那么代码应该正常closures并授予访问权限,如果REST API回退不允许,则程序应通知用户并closures工作簿。 如果没有互联网接入,则应通知用户并closures工作簿。

我的问题是我如何编码,以便正确处理REST API响应,以便它可以正常结束或closures由于从URL的拒绝响应?

这是迄今为止的VBA代码:

Private Sub Workbook_activate() Application.EnableCancelKey = xlDisabled ' Run the Error handler "ErrHandler" when an error occurs. On Error GoTo Errhandler ActiveWorkbook.FollowHyperlink Address:="https://mysite.com/licensing/getstatus.php?", NewWindow:=True ' If response is allow ' Exit the macro so that the error handler is not executed. ****what goes here??**** Exit Sub ' If response is disallow ****what goes here??**** MsgBox "Your license key is not valid. Please check your key or contact customer service." ActiveWorkbook.Close SaveChanges:=False Errhandler: ' If no Internet Access, display a message and end the macro. MsgBox "An error has occurred. You need Internet access to open the software." ActiveWorkbook.Close SaveChanges:=False End Sub 

这里是一个简单的HttpWebRequest的例子:

 Dim oRequest As Object Set oRequest = CreateObject("WinHttp.WinHttpRequest.5.1") oRequest.Open "GET", "https://mysite.com/licensing/getstatus.php?" oRequest.Send MsgBox oRequest.ResponseText 

如果你在代理之后,你可以使用这样的东西:

 Const HTTPREQUEST_PROXYSETTING_PROXY = 2 Dim oRequest As Object Set oRequest = CreateObject("WinHttp.WinHttpRequest.5.1") oRequest.setProxy HTTPREQUEST_PROXYSETTING_PROXY, "http://proxy.intern:8080" oRequest.Open "GET", "https://mysite.com/licensing/getstatus.php?" oRequest.Send MsgBox oRequest.ResponseText 

如果你想使用POST(而不是GET方法)来传递一些值到networking服务器,你可以试试这个:

 Dim oRequest As Object Set oRequest = CreateObject("WinHttp.WinHttpRequest.5.1") oRequest.Open "POST", "https://mysite.com/licensing/getstatus.php" oRequest.SetRequestHeader "Content-Typ", "application/x-www-form-urlencoded" oRequest.Send "var1=123&anothervar=test" MsgBox oRequest.ResponseText