|
- Sub getExchangeRate()
- ' 1. 创建 XMLHTTP 对象
- Dim xhr As Object
- Set xhr = CreateObject("MSXML2.XMLHTTP")
- ' 2. 设置请求参数
- Dim url As String
- url = "https://www.chinamoney.com.cn/ags/ms/cm-u-bk-currency/CurrencyPage"
- Dim beginDate As String, endDate As String
- beginDate = "2021-10-01"
- endDate = "2021-10-31"
- Dim postData As String
- postData = "{""beginDate"":""" & beginDate & """,""endDate"":""" & endDate & """,""pageSize"":""200"",""pageNum"":""1""}"
- ' 3. 发送请求
- With xhr
- .Open "POST", url, False
- ' 如果需要代理,可以在这里设置
- '.setProxy 2, "127.0.0.1:8080"
- .setRequestHeader "Content-Type", "application/json"
- .setRequestHeader "User-Agent", "Mozilla/5.0"
- .send postData
- End With
- ' 4. 解析响应内容
- Dim json As Object
- Set json = JsonConverter.Parse(xhr.responseText)
- Dim data() As Variant
- Dim headers() As String
- headers = Array("货币名称", "币种代码", "中间价", "单位", "发布日期")
- Dim rows As Object
- Set rows = json("records")
- ReDim data(1 To rows.Count, 1 To UBound(headers) + 1)
- Dim i As Long
- For i = 1 To rows.Count
- Dim row As Object
- Set row = rows(i - 1)
- data(i, 1) = row("currencyName")
- data(i, 2) = row("currencyCode")
- data(i, 3) = row("middPrice")
- data(i, 4) = row("unit")
- data(i, 5) = row("pubDate")
- Next i
- ' 5. 导出数据到Excel
- Dim wb As Workbook
- Set wb = Workbooks.Add
- With wb.Sheets(1)
- .Range("A1").Resize(1, UBound(headers) + 1).Value = headers
- .Range("A2").Resize(UBound(data, 1), UBound(data, 2)).Value = data
- .Columns.AutoFit
- End With
- End Sub
复制代码
另外,代码中使用了一个 Json 解析库 JsonConverter,需要先下载并安装该库才能运行。 |
|