在Excel VBA中,您可以使用XMLHttpRequest
对象来发送HTTP GET请求,并将值作为URL参数发送
Alt + F11
打开VBA编辑器。插入
>模块
,在模块窗口中粘贴以下代码:Function sendGetRequest(url As String, Optional params As String = "") As String
Dim http As Object
Dim urlFull As String
If params <> "" Then
urlFull = url & "?" & params
Else
urlFull = url
End If
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", urlFull, False
http.Send
If http.Status = 200 Then
sendGetRequest = http.responseText
Else
sendGetRequest = "Error: " & http.Status & " " & http.statusText
End If
Set http = Nothing
End Function
sendGetRequest
函数,将URL和所需的参数作为参数传递。例如,以下是如何调用该函数来发送GET请求到http://example.com/api
,并将参数param1
和param2
的值发送:Sub testSendGetRequest()
Dim url As String
Dim params As String
Dim response As String
url = "http://example.com/api"
params = "param1=value1¶m2=value2"
response = sendGetRequest(url, params)
MsgBox response
End Sub
请注意,此方法仅适用于发送GET请求。如果需要发送POST请求或添加其他HTTP头,您需要修改sendGetRequest
函数。另外,XMLHttpRequest
对象仅在Windows操作系统上的Excel VBA中可用。对于Mac系统,您可能需要使用其他方法,如WinHttp.WinHttpRequest.5.1
对象。
领取专属 10元无门槛券
手把手带您无忧上云