基本功能
点击刷新按钮以后,读取excel中某一列保存的股票代码,然后通过股票数据API获取实时数据,并保存到excel中。
如下图,点击刷新按钮,读取D列的股票代码,获取实时数据,并将对应的数据写入到E - L列。
基本步骤
step-1 添加按钮
通过Developer -> Insert -> Button添加刷新按钮。
然后分配宏脚本,这里新定义一个RefreshBtnClicked()。
Option Explicit
Sub RefreshBtnClicked()
'
Debug.Print "Start Refresh..."
End Sub
step-2 定义股票数据结构类
定义CStock类(class),主要目的是方便数据的结构化处理和存储。可以根据需要和使用的股票API接口返回的数据添加、删除对应字段。
Option Explicit
Public code As String '股票代码
Public name As String '股票名称
Public lastClosePrice As Double '昨收
Public openPrice As Double '今开
Public currPrice As Double '最新价格
Public maxPrice As Double '最高
Public minPrice As Double '最低
Public volume As Double '
Public turnover As Double
Public lastUpdateDate As String
Public lastUpdateTime As String
' Get current increase (%) - 获取今日涨幅
Public Property Get increaseRate() As Double
increaseRate = Round((currPrice - lastClosePrice) / lastClosePrice * 100, 2)
End Property
step-3 检查股票代码
接下来为了排除非法股票代码,通过代码首两个字母做一个简单的筛选,比如沪市(sh开头)、深市(sz开头)和港股(hk开头)。
Public Enum STOCK_MKT
MKT_HK
MKT_SH
MKT_SZ
MKT_INVALID
End Enum
'Get Market type by stock code.
Function GetMarketType(stockCode As String) As STOCK_MKT
Dim code As String
code = LCase(stockCode)
GetMarketType = MKT_INVALID
If InStr(code, "hk") = 1 Then
GetMarketType = MKT_HK
GoTo Done
End If