City Weather Report in Excel
Excel Vba code in this page gets current local weather report using free api from openweathermap. To use this code, you need these things in advance:- API key from openweathermap
- Accepted City Names
Sub GetWeatherRepor(sCity As String, sApiKey As String)
Dim oWeb As Object
Dim sURL As String
Dim oSh As Worksheet
'Weather Report API URL
'units=metric - Celcius
'units=imperial - Farenheit
sURL = "http://api.openweathermap.org/data/2.5/weather?q=" & sCity & "&units=imperial&appid=" & sApiKey
'Create Object to get data from web
Set oWeb = CreateObject("Microsoft.XMLHTTP")
'Extract Weather Data from Api
oWeb.Open "GET", sURL, False
oWeb.send
'Prase Temperature Data
sJSONData = oWeb.responsetext
sJSONData = VBA.Replace(sJSONData, ":", ",", , , vbTextCompare)
sJSONData = VBA.Replace(sJSONData, "}", ",", , , vbTextCompare)
sJSONData = VBA.Replace(sJSONData, """", ",", , , vbTextCompare)
vdata = VBA.Split(sJSONData, ",", , vbTextCompare)
'Display Important Weather Report Parameters
For i = 0 To UBound(vdata)
Select Case vdata(i)
Case "temp"
Debug.Print "Temperature: " & vdata(i + 2)
Case "description"
Debug.Print "Description: " & vdata(i + 3)
Case "pressure"
Debug.Print "Pressure: " & vdata(i + 2)
Case "humidity"
Debug.Print "Humidity: " & vdata(i + 2)
End Select
Next
End Sub
The above example gets JSON data from the API & parses few weather parameters like temperature, pressure, humidity etc., directly through string operations.
This is not the right way to do this The returned data is in JSON format.