Today, I will share code that sends <span>HTTP</span> requests through <span>Excel</span> to retrieve web resources.
Function BytesToBString(Body, Cset)
On Error Resume Next
'"GB2312"
'"GBK"
'"UTF-8"
' Excel byte encoding conversion
Dim Objstream
Set Objstream = CreateObject("adodb.stream")
Objstream.Type = 1
Objstream.Mode = 3
Objstream.Open
Objstream.Write Body
Objstream.Position = 0
Objstream.Type = 2
Objstream.Charset = Cset
BytesToBString = Objstream.ReadText
Objstream.Close
Set Objstream = Nothing
End Function
Function HttpGet(Target As Range) As String
' HTTP GET
Dim Client As New WebClient
Dim Url As String
Url = Target.Value
Dim web_Request As New WebRequest
web_Request.Resource = Url
web_Request.Format = WebFormat.Json
web_Request.Method = WebMethod.HttpGet
Dim Response As New WebResponse
Set Response = Client.Execute(web_Request)
Dim ResponseText As String
ResponseText = BytesToBString(Response.Body, "UTF-8")
HttpGet = ResponseText
End Function
<span>HttpGet</span> depends on the VBA-Web[1] library. You need to first copy <span>VBA-Web</span> into the Excel file, and then copy the above code into the file. It will be ready to use.
For example, to retrieve the content of the Baidu homepage:
=HttpGet("https://www.baidu.com")
References
[1]
VBA-Web: https://github.com/VBA-tools/VBA-Web