分享一段VBA,Excel获取实时股票数据
2017-06-14 本文已影响901人
诗与星空
因为还没有熟练掌握用Ruby生成excel的技能,所以干脆学了一点VBA,写了段通过excel实时获取股票数据的代码。
方便在excel里使用各种公式计算涨跌幅。
分享如下:
Sub test()
For r = 3 To Range("A1").CurrentRegion.Rows.Count
dm = Cells(r, 1).Value
If Val(dm) = sh000001 Then '判断上证还是深证,规则比较简单,无法准确判断创业板
URL = "http://qt.gtimg.cn/q=" & dm '从腾讯证券接口获取数据
Else
If Val(dm) < 600000 Then
URL = "http://qt.gtimg.cn/q=sz" & dm
Else
URL = "http://qt.gtimg.cn/q=sh" & dm
End If
End If
With CreateObject("msxml2.xmlhttp") '打开腾讯接口数据
.Open "GET", URL, False
.send
sp = Split(.responsetext, "~")
If UBound(sp) > 3 Then '把腾讯证券接口的数据分别写入excel对应单元格
Cells(r, 2).Value = sp(1)
Cells(r, 4).Value = sp(3)
Cells(r, 5).Value = Format(sp(30), "0000-00-00 00:00:00")
Cells(r, 6).Value = sp(4)
Cells(r, 7).Value = sp(5)
Else
Cells(r, 3).Value = "代码错啦!"
End If
End With
Next
End Sub
效果如下:
